博客
关于我
Python网络爬虫基础进阶到实战教程
阅读量:797 次
发布时间:2023-03-07

本文共 3014 字,大约阅读时间需要 10 分钟。

网络爬虫是程序自动化获取网页信息的方式,通过网络爬虫,我们可以方便地获取互联网上的数据,如网页链接、文本、图片、音频、视频等。HTML页面是网页的基础结构,由标签和内容组成,标签通过属性定位元素,CSS控制样式,JavaScript实现动态效果。

Requests模块实战

Requests是Python的HTTP库,提供简洁接口进行HTTP请求。GET请求常用于获取静态网页信息,使用requests.get()方法发送GET请求。以下代码示例:

import requests
url = 'https://www.baidu.com'
response = requests.get(url)
print(response.text)

Post请求与实战

POST请求将参数放在请求体中,通常比GET更安全。使用requests.post()方法发送POST请求:

import requests
url = 'http://xxxx.org/post'
data = {'key1': 'value1', 'key2': 'value2'}
response = requests.post(url, data=data)
print(response.text)

XPath解析

XPath用于解析XML文档,在Python中使用lxml库。以下代码示例:

from lxml import etree
url = 'https://www.baidu.com'
html = requests.get(url).text
selector = etree.HTML(html)
result = selector.xpath('//title/text()')
print(result[0])

BeautifulSoup详讲

BeautifulSoup是解析HTML和XML文档的强大库。以下代码示例:

from bs4 import BeautifulSoup
html_doc = """这是标题

第一段落

第二段落

"""
soup = BeautifulSoup(html_doc, 'html.parser')
title = soup.title.string
print(title)
for p in soup.body.find_all('p'):
print(p.string)

正则表达式

正则表达式匹配字符串模式,常用在文本处理中。以下代码示例:

import re
text = '2019年GDP增速为7.5%,同比增长0.3个百分点;CPI同比上涨2.5%,环比上涨0.3%。'
pattern1 = r'\d+.\d+%'
pattern2 = r'[A-Z]+'
num_list = re.findall(pattern1, text)
unit_list = re.findall(pattern2, text)
for i in range(len(num_list)):
print(f'{num_list[i]} {unit_list[i]}')

字体反爬

字体反爬通过加密混淆文本防止爬取。常用方法包括解析woff文件、使用fontTools库、在线工具等。以下代码示例:

import base64
from fontTools.ttLib import TTFont
font_url = 'http://example.com/font.woff'
font_base64 = '...' # 下载后的base64编码字符串
with open('font.woff', 'wb') as f:
font_data = base64.b64decode(font_base64)
f.write(font_data)
font = TTFont('font.woff')
cmap = font.getBestCmap()
replace_dict = {
'连': '0', '': '1', '﫵': '2', '': '3', '': '4',
'': '5', '': '6', '': '7', '倫': '8', '': '9'
}
text = ''
for key, value in replace_dict.items():
text = text.replace(key, value)
print(text)

Scrapy入门

Scrapy是Python的高效爬虫框架。以下代码示例:

import scrapy
class DoubanMovieSpider(scrapy.Spider):
name = 'douban_movie'
allowed_domains = ['movie.douban.com']
start_urls = ['https://movie.douban.com/top250']
def parse(self, response):
for info in response.xpath('//div[@class="info"]'):
yield {
'title': info.xpath('div[@class="hd"]/a/span/text()').extract_first(),
'score': info.xpath('div[@class="bd"]/div[@class="star"]/span[@class="rating_num"]/text()').extract_first(),
'director': info.xpath('div[@class="bd"]/p/text()')[0].strip() if len(info.xpath('div[@class="bd"]/p')) == 2 else '',
'year': info.xpath('div[@class="bd"]/p/text()')[-1].strip().replace('(', '').replace(')', '') if len(info.xpath('div[@class="bd"]/p')) == 2 else info.xpath('div[@class="bd"]/p/text()')[-1].strip()
}
next_page = response.xpath('//span[@class="next"]/a/@href')
if next_page:
yield scrapy.Request(url=response.urljoin(next_page.extract_first()), callback=self.parse)

通过以上代码示例,可以快速上手网络爬虫技术,灵活处理各种网页数据。

转载地址:http://qcofk.baihongyu.com/

你可能感兴趣的文章
python 列表函数
查看>>
Python 列表删除相同的元素
查看>>
python 列表生成式
查看>>
Python 列表解析 大文件
查看>>
python 列表转字典方法
查看>>
Python 列表(List)概述-ChatGPT4o作答
查看>>
Python网络爬虫基础进阶到实战教程
查看>>
Python 初学者需要知道的四条建议
查看>>
Python 判断字符串是否包含子字符串
查看>>
python 判断当前时间是否为零点
查看>>
python 利用pandas读取本地中CSV文件的指定列 列名重命名 并保存回本地
查看>>
python 利用pyspark读取HDFS中CSV文件的指定列 列名重命名 并保存回HDFS
查看>>
python 利用pyttsx3文字转语音
查看>>
python 利用已有Ner模型进行数据清洗合并
查看>>
python 到大数据开发工程师_如何成为一个大数据开发工程师?
查看>>