用python优化以下代码import requestsfrom bs4 import BeautifulSoup# Google搜索引擎的URLurl = httpswwwgooglecomsearchq=# 要搜索的关键字keyword = inurlueditor or cn# 构造请求头headers = User-Agent Mozilla50 Windows NT 100; W
import requests from bs4 import BeautifulSoup
Google搜索引擎的URL
url = 'https://www.google.com/search?q='
要搜索的关键字
keyword = 'inurl:/ueditor or .cn'
构造请求头
headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
发送GET请求并获取响应
response = requests.get(url + keyword, headers=headers)
解析响应文本
soup = BeautifulSoup(response.text, 'html.parser')
查找所有的搜索结果链接
links = soup.select('a[href^="http"][href*=".cn"], a[href^="http"][href*="inurl:/ueditor"]')
存储结果
results = [link.get('href') for link in links]
将结果写入文件
with open('result.txt', 'w', encoding='utf-8') as f: f.write('\n'.join(results))
输出结果
print('共找到{}个结果,已保存到result.txt文件中'.format(len(results)))
原文地址: https://www.cveoy.top/t/topic/bdAB 著作权归作者所有。请勿转载和采集!