给我一个python网页爬虫代码,关键词可以自定义的
时间: 2024-06-07 21:11:47 浏览: 19
好的,以下是一个简单的python网页爬虫代码,可以根据自定义的关键词搜索百页面并将搜索结果打印出来:
```python
import requests
from bs4 import BeautifulSoup
def search(keyword):
url = 'https://www.baidu.com/s'
params = {'wd': keyword}
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'}
response = requests.get(url, headers=headers, params=params)
soup = BeautifulSoup(response.text, 'html.parser')
results = soup.find_all('h3', {'class': 't'})
for result in results:
print(result.a.text)
search('Python爬虫')
```
这个代码使用了requests和BeautifulSoup库,通过requests库发送GET请求获取搜索结果页面,然后使用BeautifulSoup库解析页面并找出所有标题为h3且class为t的元素,打印出其下的a标签的文本内容。你可以自定义搜索的关键词,比如这里的'Python爬虫'。