To achieve the same functionality in Dart, you can use the http package to make network requests and the html package to parse and manipulate HTML content. Below is a Dart script that replicates the Python script functionality by using these packages.
First, make sure to add the necessary dependencies to your pubspec.yaml file:
dependencies:
http: ^0.13.4
html: ^0.15.0
Then, you can write a Dart script like this:
import 'package:http/http.dart' as http;
import 'package:html/parser.dart' show parse;
import 'package:html/dom.dart';
void main() async {
final url = 'https://inv.nadeko.net/channel/UChXcfyCJ4LWq8iuUqttdy0Q';
final baseUrl = 'https://inv.nadeko.net/';
final headers = {
'User-Agent':
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
};
final response = await http.get(Uri.parse(url), headers: headers);
if (response.statusCode == 200) {
var document = parse(response.body);
var divContents = document.querySelectorAll('.pure-u-1.pure-u-md-1-4');
for (var content in divContents) {
var videoCardRow = content.querySelector('.video-card-row');
if (videoCardRow != null) {
var link = videoCardRow.querySelector('a');
var paragraph = videoCardRow.querySelector('p');
var thumbnail = content.querySelector('.thumbnail');
var img = thumbnail?.querySelector('img');
var imgSrc = img != null ? '$baseUrl${img.attributes['src']}' : null;
if (link != null && paragraph != null && imgSrc != null) {
print('${baseUrl}${link.attributes['href']} ${paragraph.text} Image URL: $imgSrc');
}
}
}
} else {
print('Failed to load page. Status code: ${response.statusCode}');
}
}
Explanation:
- Dependencies: The
http package is used to handle HTTP requests while the html package is used to parse and interact with the HTML content.
- Request: Similar to the Python script, an HTTP GET request is made to the URL with headers to mimic a browser request.
- Parsing HTML: The response is parsed using
html.parse to create a document structure that allows querying and manipulation of elements.
- Data Extraction: A loop iterates through all elements with the class specified, checks for a 'video card' and extracts the relevant data similar to the Python script.
- Output: The output format uses string interpolation to construct and print the URLs and associated text.
To run this Dart script, you need to ensure Dart is correctly set up in your development environment and all dependencies specified in pubspec.yaml are resolved with pub get.