写一份爬取百度网页的python代码
时间: 2024-01-14 15:04:12 浏览: 19
以下是一个简单的Python代码,用于爬取百度网页的搜索结果:
```python
import requests
from bs4 import BeautifulSoup
# 搜索关键词
keyword = "Python"
# 构造搜索url
url = "https://www.baidu.com/s?wd=" + keyword
# 发送请求,获取页面内容
response = requests.get(url)
html = response.content
# 解析页面内容,获取搜索结果
soup = BeautifulSoup(html, 'html.parser')
results = soup.find_all('div', {'class': 'result'})
# 输出搜索结果
for result in results:
title = result.find('h3').get_text()
link = result.find('a')['href']
print(title, link)
```
简要解释:
1. 首先导入需要的库:`requests` 用于发送HTTP请求,`beautifulsoup4` 用于解析HTML页面的内容。
2. 确定搜索关键词,构造搜索url。
3. 发送HTTP请求,获取页面内容。
4. 解析HTML页面内容,使用 `find_all` 方法找到搜索结果的 `div` 标签。
5. 对于每个搜索结果,使用 `find` 方法找到标题和链接,分别输出。
相关问题
写一段爬取天气的python代码
可以使用第三方库 requests 和 BeautifulSoup 来爬取天气信息。代码如下:
```
import requests
from bs4 import BeautifulSoup
def get_weather(city_name):
# 请求 URL
url = f'https://www.google.com/search?q={city_name}天气'
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)
response.raise_for_status()
# 解析网页数据
soup = BeautifulSoup(response.text, 'lxml')
weather_info = soup.select_one('#wob_tm').text
weather = soup.select_one('#wob_dc').text
return weather_info, weather
city_name = '北京'
weather_info, weather = get_weather(city_name)
print(f'{city_name}的天气:{weather_info} {weather}')
```
这段代码实现了通过爬取 Google 搜索的天气结果来获取天气信息。
用python写一段爬取百度图片的代码
以下是一段用 Python 爬取百度图片的代码:
```python
import requests
import re
import os
def get_image(keyword):
url = 'https://image.baidu.com/search/index?tn=baiduimage&word=' + keyword
html = requests.get(url).text
pic_url = re.findall('"objURL":"(.*?)",', html, re.S)
i = 1
for each in pic_url:
print(each)
try:
pic = requests.get(each, timeout=10)
except requests.exceptions.ConnectionError:
print('【错误】当前图片无法下载')
continue
string = 'pictures/' + keyword + '_' + str(i) + '.jpg'
fp = open(string, 'wb')
fp.write(pic.content)
fp.close()
i += 1
if __name__ == '__main__':
if not os.path.exists('pictures'):
os.mkdir('pictures')
get_image('猫')
```
这段代码可以爬取百度图片中关键词为“猫”的图片,并保存在本地的“pictures”文件夹中。