编写一段Python代码,向百度提交查询关键词“桃花源记”,抓取百度的查询结果,要求有文字、链接,可以在浏览器中打开抓取的链接,或者调用浏览器打开抓取的链接。

红框内是根据网站信息需要更改的内容。57031baa3a394395be479ad89f1ff15e.png

附上完整代码:

import json
import requests
from lxml import etree
headers = {
    "User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) "
                 "Chrome/88.0.4324.104 Safari/537.36"
}
response = requests.get('https://www.baidu.com/s?wd=桃花源记&lm=0', headers=headers)
r = response.text
html = etree.HTML(r, etree.HTMLParser())
r1 = html.xpath('//h3')
r2 = html.xpath('//*[@class="content-right_8Zs40"]')
r3 = html.xpath('//*[@class="c-row source_1Vdff OP_LOG_LINK c-gap-top-xsmall"]/a/@href')
for i in range(4):
    r11 = r1[i].xpath('string(.)')
    r22 = r2[i].xpath('string(.)')
    r33 = r3[i]
    with open('桃花源记.txt', 'a', encoding='utf-8') as c:
        c.write(json.dumps(r11,ensure_ascii=False) + '\n')
        c.write(json.dumps(r22, ensure_ascii=False) + '\n')
        c.write(json.dumps(r33, ensure_ascii=False) + '\n')
    print(r11, end='\n')
    print('------------------------')
    print(r22, end='\n')
    print(r33)

结果截图:

75fb355d72c6409a9eb31af6e39aa4fd.png

 

 

Logo

华为云1024程序员节送福利,参与活动赢单人4000元礼包,更有热门技术干货免费学习

更多推荐