本文共 3014 字,大约阅读时间需要 10 分钟。
网络爬虫是程序自动化获取网页信息的方式,通过网络爬虫,我们可以方便地获取互联网上的数据,如网页链接、文本、图片、音频、视频等。HTML页面是网页的基础结构,由标签和内容组成,标签通过属性定位元素,CSS控制样式,JavaScript实现动态效果。
Requests是Python的HTTP库,提供简洁接口进行HTTP请求。GET请求常用于获取静态网页信息,使用requests.get()方法发送GET请求。以下代码示例:
import requestsurl = 'https://www.baidu.com'response = requests.get(url)print(response.text)
POST请求将参数放在请求体中,通常比GET更安全。使用requests.post()方法发送POST请求:
import requestsurl = 'http://xxxx.org/post'data = {'key1': 'value1', 'key2': 'value2'}response = requests.post(url, data=data)print(response.text) XPath用于解析XML文档,在Python中使用lxml库。以下代码示例:
from lxml import etreeurl = 'https://www.baidu.com'html = requests.get(url).textselector = etree.HTML(html)result = selector.xpath('//title/text()')print(result[0]) BeautifulSoup是解析HTML和XML文档的强大库。以下代码示例:
from bs4 import BeautifulSouphtml_doc = """这是标题 第一段落
第二段落
"""soup = BeautifulSoup(html_doc, 'html.parser')title = soup.title.stringprint(title)for p in soup.body.find_all('p'): print(p.string)
正则表达式匹配字符串模式,常用在文本处理中。以下代码示例:
import retext = '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 base64from fontTools.ttLib import TTFontfont_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是Python的高效爬虫框架。以下代码示例:
import scrapyclass 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/