python爬虫爬取百度代码
时间: 2023-12-05 21:05:10 浏览: 59
Python爬虫可以用来爬取百度搜索结果中的内容,包括文本和图片等。以下是一个简单的示例代码:
```
import requests
from bs4 import BeautifulSoup
# 搜索关键词
keyword = 'Python'
# 构造搜索链接
url = 'https://www.baidu.com/s?wd=' + keyword
# 发送请求并获取响应
response = requests.get(url)
# 解析响应内容
soup = BeautifulSoup(response.text, 'html.parser')
# 获取搜索结果列表
results = soup.find_all('div', class_='result')
# 遍历搜索结果并输出标题和链接
for result in results:
title = result.h3.text
link = result.a['href']
print(title, link)
```
这段代码可以爬取百度搜索结果中与关键词“Python”相关的内容,并输出每个搜索结果的标题和链接。如果需要爬取图片,可以使用类似的方法,先获取图片链接,再下载图片并保存到本地。
相关问题
python爬虫爬取百度文库
Python爬虫可以爬取百度文库的文档,具体步骤如下:
1. 安装requests和BeautifulSoup模块:在Python中,可以使用requests模块获取网页源代码,使用BeautifulSoup模块解析网页。
2. 获取文档ID:在百度文库中,每个文档都有一个唯一的ID。可以通过在浏览器中打开文档,查看URL地址中的文档ID来获取。
3. 构造URL地址:百度文库的文档地址格式为:https://wenku.baidu.com/view/文档ID.html,其中文档ID为第二步获取到的。使用requests模块访问该地址,获取网页源代码。
4. 解析网页源代码:使用BeautifulSoup模块解析网页源代码,获取文档内容。
下面是一个简单的示例代码:
```python
import requests
from bs4 import BeautifulSoup
# 获取文档ID
doc_id = 'xxxxxx'
# 构造URL地址
url = 'https://wenku.baidu.com/view/{}.html'.format(doc_id)
# 发送请求,获取网页源代码
response = requests.get(url)
html = response.text
# 解析网页源代码,获取文档内容
soup = BeautifulSoup(html, 'html.parser')
content = soup.find_all(class_='reader-word-layer')
# 输出文档内容
for item in content:
print(item.text)
```
需要注意的是,爬虫爬取他人网站内容可能涉及到法律问题,请谨慎使用。另外,百度文库有一些文档是需要付费才能查看的,这些文档是无法通过爬虫免费获取的。
代码 Python爬虫 爬取百度网照片
爬取百度网的照片需要用到爬虫技术和Python的相关库。以下是一个简单的爬虫程序示例,可以爬取百度图片的搜索结果中的前10张图片并保存到本地:
```python
import requests
import re
# 定义要爬取的关键词和数量
keyword = '猫'
num = 10
# 定义请求头
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'}
# 构造请求URL
url = 'https://image.baidu.com/search/acjson'
params = {'tn': 'resultjson_com', 'ipn': 'rj', 'ct': 201326592, 'is': '', 'fp': 'result', 'queryWord': keyword,
'cl': 2, 'lm': -1, 'ie': 'utf-8', 'oe': 'utf-8', 'adpicid': '', 'st': -1, 'z': '', 'ic': 0, 'word': keyword,
's': '', 'se': '', 'tab': '', 'width': '', 'height': '', 'face': 0, 'istype': 2, 'qc': '', 'nc': 1,
'fr': '', 'expermode': '', 'force': '', 'pn': 0, 'rn': num, 'gsm': '1e'}
# 发送HTTP请求并解析响应信息
response = requests.get(url, params=params, headers=headers)
data = response.json().get('data')
# 遍历解析出的图片信息并下载
for item in data:
if item.get('thumbURL') is not None:
thumb_url = item.get('thumbURL')
pic_url = re.sub(r'thumb', 'large', thumb_url)
response = requests.get(pic_url, headers=headers)
with open(keyword + '.jpg', 'ab') as f:
f.write(response.content)
print('下载完成!')
```
在程序中,我们首先定义了要爬取的关键词和数量,然后构造了请求URL,发送HTTP请求并解析响应信息。最后遍历解析出的图片信息并下载到本地。需要注意的是,在下载图片时需要将缩略图URL替换为大图URL,并且使用二进制写入方式将图片内容写入文件。