爬取百度

百度V百科爬取所有问题&回答

哎,直接上代码

import requests
import re
from lxml import etree
import time
headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36 Edg/84.0.522.52'}
def get_url(v_url):
    #url='https://baike.baidu.com/api/vbaike/knowledgelist?count=8&page=1&keyWord='
    html=requests.get(url=v_url,headers=headers)
    html.encoding='utf-8'
    html=html.text
    urls=re.findall('"link":"(.*?)"',html,re.S)
    for url in urls:
        url=url.replace('\\','')
        get_info(url)
def get_info(url):
    #url='https://baike.baidu.com/tashuo/browse/content?id=a2db9e0a9a02aef4eeb7778a'
    html=requests.get(url=url,headers=headers)
    html.encoding='utf-8'
    html=html.text
    html=etree.HTML(html)
    title=html.xpath('//*[@id="article"]/div[1]/text()')[0].replace('\n','')
    content1=html.xpath('//*[@id="article"]/div[4]/p/text()')
    content2=html.xpath('//*[@id="article"]/div[3]/p/text()')
    content=content1+content2
    text=''
    for info in content:
        info=info.replace('@','')
        text=text+info
    main=title+'@'+text
    write(main,title)
def write(main,key):
    f = open("秒懂百科冷知识.txt",'a',encoding="utf-8") #在运行目录创建一个TXT文本存储结果并追加模式打开
    f.write(main+"\n") #保存结果
    f.close() #关闭句柄
    print("=======================\n"+key+"++采集并输出完毕"+"\n=======================\n") #把采集的进度显示
    time.sleep(2)
a=1
for a in range(1,40):
    v_url='https://baike.baidu.com/api/vbaike/knowledgelist?count=8&page={}&keyWord='.format(a)
    print('=========================================\n'+'正在下载第{}页'.format(a)+'\n=========================================\n')
    get_url(v_url)
    print('=========================================\n'+'下载完成第{}页'.format(a)+'\n=========================================\n')

对了,补充一句,亲测可用,人头担保!!!!!

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值