利用Python爬虫,写爬百度温度的代码
时间: 2024-02-16 15:27:48 浏览: 14
好的,以下是爬取百度温度的Python代码:
```python
import requests
from bs4 import BeautifulSoup
url = 'https://www.baidu.com/s?wd=%E7%99%BE%E5%BA%A6%E6%B8%A9%E5%BA%A6'
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)
soup = BeautifulSoup(response.text, 'html.parser')
temp = soup.select('.op_weather4_twoicon_num')[0].getText()
print('当前温度为:' + temp + '℃')
```
这段代码首先使用requests库发送GET请求获取百度温度页面的HTML代码,然后使用BeautifulSoup库解析HTML代码,找到当前温度所在的标签并提取温度值,最后输出温度值。
相关问题
利用python写一个爬虫基础代码
当然可以,以下是一个基础的 Python 爬虫示例代码,可以用来爬取网站的页面内容:
```python
import requests
# 发送 HTTP 请求
url = 'https://www.example.com'
response = requests.get(url)
# 输出网页内容
print(response.text)
```
这个示例代码使用了 Python 的 requests 库来发送 HTTP 请求,获取网页内容。您只需要将 url 替换成您要爬取的网站的地址即可。当然,这只是一个最基础的爬虫代码,如果您需要爬取更多的内容,还需要学习更多的爬虫知识。
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数据。最后,返回翻译结果。