要爬取搜索后的网页,可以使用Python中的爬虫库(如Requests、BeautifulSoup、Scrapy等)来发送HTTP请求并解析网页内容。
下面是一个使用Requests和BeautifulSoup来爬取搜索后的网页的示例:
import requests from bs4 import BeautifulSoup # 设置请求头 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' } # 发送HTTP请求并获取响应内容 def get_search_results(keyword): url = 'https://www.example.com/search?q=' + keyword response = requests.get(url, headers=headers) return response.text # 解析网页内容,提取需要的信息 def parse_search_results(html): soup = BeautifulSoup(html, 'html.parser') results = soup.find_all('div', class_='result') for result in results: title = result.find('h3').text link = result.find('a')['href'] print('Title:', title) print('Link:', link) print('---') # 搜索关键词并爬取搜索结果 keyword = 'Python' html = get_search_results(keyword) parse_search_results(html)
在代码中,首先定义了一个get_search_results
函数,用于发送HTTP请求并返回搜索结果的HTML内容。然后定义了一个parse_search_results
函数,用于解析HTML内容,找到搜索结果中的标题和链接,并进行输出。
最后,调用get_search_results
函数传入关键词,获取搜索结果的HTML内容,然后调用parse_search_results
函数解析HTML内容,输出搜索结果的标题和链接。
注意:在实际爬取过程中,应该遵守网站的爬取规则和法律法规,不要对目标网站造成过大的负担,可以设置合适的请求头、限制请求频率等。