|
|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 LUYAO123 于 2019-5-10 21:20 编辑
本人新手入门,在学习动态页面爬取时遇到两个问题:1.某网站第一页的消息点入后还是在这一页,2.网站有些网址用浏览器访问本身就是403,要如何剔除。求求大佬帮我看看
import requests
from bs4 import BeautifulSoup
import time
#实现根据url进行网页爬取,并得到想要的文本信息,保存在一个文件列表txtlist中。
def gethtml(url,deep,txtlist):
headers = {
'Connection' : 'keep-alive',
'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
'Accept-Language' : 'zh-CN,zh;q=0.9',
'Accept-Encoding' : 'gzip, deflate',
'Host' : 'www.cnfood.cn',
'User-agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36',
'Cookie' : 'PHPSESSID=2g3gdp9hi6dtou2t5iq1ub3437; stattraffic_sitekeyword=%E9%A3%9F%E5%93%81%2C%E4%B8%AD%E5%9B%BD%E9%A3%9F%E5%93%81%E6%8A%A5%E7%BD%91+%2C%E4%B8%AD%E5%9B%BD%E9%A3%9F%E5%93%81%E6%8A%A5+%2C%E9%A3%9F%E5%93%81%E8%A1%8C%E4%B8%9A%EF%BC%8C%E9%A3%9F%E5%93%81%E6%8A%A5%EF%BC%8C%E9%A3%9F%E5%93%81%E5%AE%89%E5%85%A8; Hm_lvt_c86a1a3b013d27167c4c86dc553cc86d=1557400863; UM_distinctid=16a9c53497639f-0b28ea05bb2227-7a1437-100200-16a9c534977384; CNZZDATA1273628067=852743444-1557397358-https%253A%252F%252Fwww.baidu.com%252F%7C1557402764; Hm_lpvt_c86a1a3b013d27167c4c86dc553cc86d=1557404147',
}#请求头的书写,包括User-agent,Cookie等
try:
for i in range(deep):
print('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>',deep-i)
r = requests.get(url+str(100-i)+'.html',headers = headers,timeout=30)
if r.status_code == 200:
r.encoding = r.apparent_encoding
r.raise_for_status()
soup = BeautifulSoup(r.text,'html.parser')
a = soup.find_all('div',class_='media-body')
for b in a:
c = b.find_all('a')
print(c[0].text,c[0]['href'])
#将爬取的文章标题和正文链接添加进txtlist变量中
txtlist.append('>>>>>>>'+c[0].text+'\n'+c[0]['href']+'\n')
#通过request将正文链接进入正文,爬取正文。
#if c[0]['href']!=NULL:遇到问题某些网址没有二层界面网址
r1 = requests.get(c[0]['href'], timeout=30)
if r.status_code == 200:
r1.raise_for_status()#解决不了403问题
r1.encoding = r1.apparent_encoding
soup1 = BeautifulSoup(r1.text,'html.parser')
a1 = soup1.find_all('div',class_='ueditor-content')
# print(a)
for b1 in a1:
c1 = b1.find_all('p')
for e1 in c1:
print(e1.text)
#将每篇的正文再次赋予txtlist变量
txtlist.append(e1.text)
i += 1
except:
print('有错误发生')
return
#将txtlist列表中的数据保存到D盘112.txt文件中。
def savefile(txt):
try:
with open('D:\新建文件夹\新闻6.txt', 'a', encoding='utf-8') as f:
timenow = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
print(timenow)
f.write('>>文章爬取时间>>' + timenow + '>>>>>>>' + txt + '\n')
except:
print('有错误未能存盘')
return
#调用的主函数
def main():
deep = 100 #定义要抓取多少层页面
url = 'http://www.cnfood.cn/hangyejiandu_'
txtlist = []
gethtml(url,deep,txtlist)
txt = ''.join(txtlist) #将列表文件变成字符串文件,便于进行保存。
print(txt)
savefile(txt)
main()
|
|