python3爬百度代码
时间: 2023-10-25 20:03:23 浏览: 50
下面是一个使用Python3爬取百度网页的示例代码:
```python
import requests
def crawl_baidu():
url = 'https://www.baidu.com'
response = requests.get(url) # 发送GET请求
if response.status_code == 200: # 请求成功
print(response.text) # 打印响应内容
else:
print('请求失败')
if __name__ == '__main__':
crawl_baidu()
```
以上是一个简单的爬虫示例,使用了Python的requests库发送GET请求,并获取百度首页的响应内容。在代码中,我们首先定义了要爬取的URL为"https://www.baidu.com",然后使用requests库的`get()`方法发送GET请求,并将返回的响应保存在`response`变量中。通过`response.status_code`可以获取请求的状态码,如果为200表示请求成功,可以通过`response.text`获取响应的文本内容。最后,通过判断状态码,我们可以打印出百度首页的内容或者打印请求失败的提示信息。
当运行代码时,将会输出百度首页的HTML源代码。需要注意的是,爬取网页时应该遵守网站的爬虫规则,不得频繁请求或过度抓取。
相关问题
python爬虫百度翻译代码
以下是一个简单的Python爬虫实现百度翻译的代码,它使用了requests和json库:
```python
import requests
import json
def translate(content):
url = 'https://fanyi.baidu.com/sug'
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'}
data = {
'kw': content
}
response = requests.post(url, data=data, headers=headers)
result = json.loads(response.text)
return result['data'][0]['v']
```
这个代码使用了requests库发送POST请求,传入待翻译的内容作为参数,获取百度翻译的结果。其中,headers是模拟浏览器的请求头,data是POST请求的参数,response是服务器返回的响应,result是响应的JSON数据。最后,返回翻译结果。
python百度爬虫代码
以下是一个简单的Python百度爬虫代码示例:
```python
import requests
from bs4 import BeautifulSoup
# 搜索关键字
keyword = 'Python'
# 搜索起始页码
start_page = 0
# 搜索结果数
result_num = 10
# 构造搜索链接
search_url = f'https://www.baidu.com/s?wd={keyword}&pn={start_page}&rn={result_num}'
# 发送HTTP请求
response = requests.get(search_url)
# 解析HTML页面
soup = BeautifulSoup(response.content, 'html.parser')
# 查找所有搜索结果的标题和链接
results = soup.find_all('h3', class_='t')
for result in results:
# 获取标题和链接
title = result.a.get_text()
link = result.a['href']
# 打印搜索结果
print(title)
print(link)
```
该代码使用requests库发送HTTP请求,使用BeautifulSoup库解析HTML页面,然后查找所有搜索结果的标题和链接,并打印输出。你可以根据自己的需求修改关键字、起始页码和搜索结果数等参数来进行搜索。