一个很小的爬虫,演示了爬一首词,后存进txt文件中去

一个很小的爬虫,演示了爬一首词,后对数据进行清洗,后存进txt文件中去

import requests,re
from bs4 import BeautifulSoup

url="https://trade.500.com/sfc/"
url2="https://so.gushiwen.org/shiwenv_4d3b4d132c82.aspx"

req=requests.get(url2)
if req.status_code==200:
if req.encoding=="gbk" or req.encoding=="ISO-8859-1":
html = req.content.decode("GBK")
else:
html=req.text

soup = BeautifulSoup(html, 'lxml')

# 使用正则来查找
# 查找标签是h1-h7的所有数据
# result=soup.findAll(re.compile("h[1-7]"))
# 查找标签是a的所有数据,加一个找内容包含有“500”字的所有标签与内容
# result2=soup.findAll("a",text=re.compile(".*(500)+.*"))
#查找外链的相关信息,即href="http://..."或"https://..."
# result3=soup.findAll("a",attrs={"href":re.compile("^(http\:)|^(https\:).*")})

#使用导航树来查找
# soup.body.children
# soup.body.descendants
# soup.body.find("div").next_siblings
# soup.body.find("div").parent

#得到所有源码
# print(soup)
#获取标题:
title=soup.findAll("h1")
title=[x.text for x in title]
title="".join(title)
print(title)
#获取内容:
# content=soup.body.findAll("div",id="contson4d3b4d132c82")
content=soup.body.findAll("div",attrs={"id":"contson4d3b4d132c82"}) #效果同上一句
content=[x.text for x in content]

#数据内容清洗:
content = "".join(content).strip() #去空格
# content=re.sub("原字符","替换的字符",content)
# content=re.sub("\(.*?\)","",content) #.*?是懒惰匹配,不用?就是无敌匹配
print(content)

#最后写入txt文件中
with open(f"{title}.txt","w",encoding="utf-8") as f:
f.write(title+"\n"+content)




else:
print("连接不成功,请检查程序及网络?")












猜你喜欢

转载自www.cnblogs.com/yiyea/p/11442405.html