Học Thuật Toàn Mạng Web
Lưu ý: Ghi chú này được viết bằng jupyter.
Kiến Thức Web Frontend
Jupyter có thể chạy trực tiếp HTML và JavaScript chỉ cần thêm %%html hoặc %%javascript vào trước mã code:
%%html
<html>
<head>
<title>Phát triển Web Scraping với Python</title>
<meta charset='UTF-8'>
</head>
<body>
Cài đặt tài liệu<br>
<p>Đây là một đoạn văn</p>
</body>
</html>
Đây là một đoạn văn
%%html
<html>
<head>
<script type='text/javascript'>
alert('Xin chào, thế giới!');
var chuoi1='xin chào';
var chuoi2 = 'thế giới';
chuoi1 += chuoi2;
alert(chuoi1);
</script>
</head>
<body>
Thu thập dữ liệu web
</body>
</html>
Thu thập dữ liệu web
%%javascript
alert('xin chào ban')
var chuoi1='xin chào';
var chuoi2 = 'thế giới';
chuoi1 += chuoi2;
alert(chuoi1);
var nguoi = {ten:'Nguyen Van A',tuoi:25};
alert(nguoi.ten)
XPath Nodes
%%html
<xml version="1.0" encoding="ISO-8859-1">
<lop>
1001
<ten lang="en">John</ten>
<nuoc>USA</nuoc>
</lop>
CSS - Bảng Kiểu Tầng
CSS bao gồm bộ chọn và một số khai báo. Thường có ba cách:
- Bảng kiểu nội tuyến, sử dụng trực tiếp thuộc tính style để thay đổi kiểu, ví dụ:
<body style='background-color:blue;margin:0;padding:0;'></body>
- Bảng kiểu nhúng, mã code được viết giữa thẻ
<style type = 'text/css'></style> - Bảng kiểu bên ngoài, CSS được viết trong một tệp riêng biệt. Sử dụng
<link rel='StyleSheet' type='text/css' href='style.css'>.
JavaScript
Hai phương thức tham chiếu:
- Nhập trực tiếp code, sử dụng
<script type='text/javascript'>alert('xin chao')</script> - Tham chiếu tệp bên ngoài sử dụng
<script src='temp/test1.js'></script>, thường đặt giữa<head></head>.
HTTP Standard
- Mã trạng thái phổ biến: 200 kết nối thành công. 301 tài nguyên được chuyển vĩnh viễn đến URL khác. 404 không tìm thấy. 500 lỗi máy chủ nội bộ.
- Thông tin header, thường dùng User-Agent, thường được dùng để chống thu thập dữ liệu.
- Sự khác biệt giữa GET và POST: GET truyền dữ liệu qua URL, dữ liệu tối đa chỉ 1024B, và tham số hiển thị trên thanh địa chỉ. POST truyền dữ liệu qua entity, không giới hạn kích thước dữ liệu, bảo mật cao hơn.
Tổng Quan Thu Thập Dữ Liệu Web với Python
Loại Thu Thập Dữ Liệu:
- Thu thập dữ liệu web tổng quát, như công cụ tìm kiếm Google, Bing.
- Thu thập dữ liệu web tập trung, chương trình tự động tải trang web.
- Thu thập dữ liệu web gia tăng, chỉ tải khi có thay đổi.
- Thu thập dữ liệu web sâu, trang web yêu cầu đăng nhập mới có thể truy cập.
Thực Hiện Yêu Cầu HTTP với Python
import urllib
response = urllib.request.urlopen('http://www.vietnamnet.vn')
html=response.read()
print(html[0:20])
b'\nPhương thức trên là yêu cầu GET. Dưới đây là yêu cầu POST:
# encoding:utf-8 import urllib url = 'http://www.example.com/login' postdata = {b'ten_dang_nhap' : b'nguoidung', b'mat_khau' : b'matkhau123'} data = urllib.parse.urlencode(postdata).encode('utf-8') req = urllib.request.Request(url, data) response = urllib.request.urlopen(req) html = response.read() print(html[0:20])b'\nXử Lý Header Yêu Cầu
import urllib url = 'https://www.vietnamnet.vn/login' 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' referer = 'https://www.vietnamnet.vn' postdata = {'ten_dang_nhap':'nguoidung_test','mat_khau':'***'} headers = {'User-Agent':user_agent,'Referer':referer} data = urllib.parse.urlencode(postdata).encode('utf-8') req = urllib.request.Request(url,data,headers) response = urllib.request.urlopen(req) html = response.read() print(html[0:50])b'\n<html lang="vi">\n<head>\nCũng có thể sử dụng hàm add_header():
import urllib url = 'https://www.vietnamnet.vn/login' user_agent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36' referer = 'https://www.vietnamnet.vn' postdata = {'ten_dang_nhap':'nguoidung_test','mat_khau':'***'} data = urllib.parse.urlencode(postdata).encode('utf-8') req = urllib.request.Request(url) req.add_header('User-Agent',user_agent) req.add_header('Referer',referer) req.data =data response = urllib.request.urlopen(req) html = response.read() print(html[0:10])b'\r\nThư Viện Requests
import requests postdata = {' khoa ':' gia tri '} r = requests.post('https://www.vietnamnet.vn/login',data=postdata) print(r.content)b'\n<html><head>\n<title>404 Not Found</title>\n</head><body>\n<h1>Not Found</h1>\n<p>The requested URL /login was not found on this server.</p>\n</body></html>\n'Phản Hồi và Mã Hóa
import requests r = requests.get('https://www.vietnamnet.vn') print(r.encoding) r.encoding = 'utf-8' print(r.text[0:20])ISO-8859-1import chardet import requests r = requests.get('https://www.vietnamnet.vn') print(chardet.detect(r.content)) r.encoding = chardet.detect(r.content) print(r.text[0:20]){'encoding': 'utf-8', 'confidence': 0.99, 'language': ''}Ngoài phản hồi đầy đủ, còn có chế độ luồng, sẽ đọc dưới dạng byte stream:
import requests r = requests.get('https://www.vietnamnet.vn',stream=True) print(r.raw.read(10))b'\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'Xử lý header yêu cầu:
import requests 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' headers = {'User-Agent':user_agent} r = requests.get('https://www.vietnamnet.vn',headers=headers) print(r.content[0:20])b'