给出第二个爬虫实例。
- 使用 jupyter notebook 环境运行。
- 遇到中文乱码问题。
1 获取url list
import requests
import re
from bs4 import BeautifulSoup
import time,random
# 从目录页,获取链接列表
page = 'https://www.tycqzw.la/47_47107/';
headers = {
"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36",
}
respose=requests.get(page, headers);
assert respose.status_code==200,'Error: requests.get'
respose.encoding='utf-8' #主动设置编码
#respose.text
from bs4 import BeautifulSoup
soup=BeautifulSoup(respose.text,"lxml")
arr=soup.find_all("div", attrs={"id":"list"})[0].find_all("a")
arr
输出:
[<a href="/47_47107/10393894.html">第543章 尾声</a>,
<a href="/47_47107/10393893.html">第542章 忽离忽别负华年(2)</a>,
<a href="/47_47107/10393892.html">第541章 忽离忽别负华年(1)</a>,
<a href="/47_47107/10393891.html">第540章 你是我的(2)</a>,
arr2=arr[9:]
len(arr2) #543
2. 提取文本
import requests
import re
from bs4 import BeautifulSoup
import time,random
# 为防被封,不能高频访问:模拟用户的点击间隔
def pause(seconds=2):
#随机时间段后[2s,12s]执行
pause=seconds+3*random.random()
print(' sleep '+str(pause) + "second \n")
time.sleep(pause)
def write2file(url, title):
#1. get response
headers = {
"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36",
}
respose=requests.get(url, headers);
respose.encoding='utf-8'
assert respose.status_code==200,'Error: requests.get'
#2. get info
soup=BeautifulSoup(respose.text,"lxml")
patterns=soup.find_all("div", attrs={"id": "content"} )[0]
#3. write to file
fw=open('novel2.txt','a');
fw.write(title+"\n");
for item in patterns:
text=item.string
if None != text and text.strip() != "": #跳过全是空格的行
text=re.sub("校花的全能保安", "", text)
text=re.sub("推荐都市大神老施新书:", "", text)
#text=re.sub("章(.*?)\s{3,}", "章\\1\\n", text)
text=re.sub("\s{4,}", " ", text)
#print("> "+ text)
fw.write(text)
fw.write(url+"\n\n\n################\n")
# url="https://www.tycqzw.la" +arr2[0].get("href")
# title=arr2[0].string;
# print(title+"\n"+url)
# write2file(url, title)
# print("done")
3. 批量下载和提取
# get url
i=0
for ele in arr2:
i=i+1
url1="https://www.tycqzw.la" +ele.get("href");
title1=ele.string;
print( str(i) +" "+ url1+ " " + title1)
write2file(url1, title1)
pause(0.5)
print("end")
这一次有 543 个,需要的时间更多了。耐心等待即可。
针对每个网站,都要重新设计信息提取部分的代码。
最后的文本有 2.5M。
该篇内容展示了如何在jupyternotebook环境下编写Python爬虫,处理中文乱码问题,从目录页获取链接列表,然后批量下载和提取网页文本。使用requests库获取页面,BeautifulSoup解析HTML,通过正则表达式清洗数据,最终将内容写入文件。

被折叠的 条评论
为什么被折叠?



