博客
关于我
Python网络爬虫基础进阶到实战教程
阅读量:798 次
发布时间: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 rdflib可传递查询
查看>>
python redis 集群_python 搭建redis集群
查看>>
python redis连接,在Python中使用Redis连接池的正确方法
查看>>
python regex_Python RegEx
查看>>
python requests post 中文结果请求得到unicode
查看>>
Python Requests接口自动化测试实战
查看>>
Python requests模块
查看>>
python request与grequests该如何选择
查看>>
python request模块
查看>>
Python requirements.txt的使用方法
查看>>
Python REST(Web 服务)框架的推荐?
查看>>
Python rsa 加密
查看>>
Python RSA操作
查看>>
Python轻松实现统计学中重要的相关性分析
查看>>
Python scrapy 常见问题及解决 【遇到的坑】
查看>>
Python Seborn热图数据的动态更新
查看>>
Python Seborn绘制空白直方图
查看>>
Python Selenium - 获取href值
查看>>
Python Selenium实现自动化测试及Chrome驱动使用!
查看>>
Python Selenium搭建UI自动化测试框架
查看>>