from bs4 import BeautifulSoup
import bs4
import requests
import lxml
# UA 伪装
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0"
}
# 先进行首页数据的爬取
# 指定url
url = "https://so.gushiwen.org/guwen/book_106.aspx"
page_txt = requests.get(url, headers=headers).text
# 创建Beautifulsoup实例
soup = BeautifulSoup(page_txt, "lxml")
# 爬取所有的标题 注意返回一个列表
soup_lis = soup.select(".bookcont > ul > span ")
fp = open("./sanguo.txt", "w", encoding="utf-8")
# 遍历所有标题
for i in soup_lis:
# 取出标题
soup_title = i.string
# 取出标题中原文章中的url
new_url = i.a["href"] # 注意必须是这个标签的上一级.下一级
# 爬取每章中的所有数据
new_txt = requests.get(new_url, headers=headers).text
new_soup = BeautifulSoup(new_txt, "lxml") # 重新生成一个实例
all = new_soup.find("div", class_="contson").text # 注意这里可以使用find,因为原文章的作品只在这个标签下面
fp.write(soup_title + "\n" + all)
print("爬取完成!!")
fp.close()
简单的文章爬取(Python)
最新推荐文章于 2024-05-03 18:58:10 发布