.shtml的python网页爬虫代码
时间: 2024-03-10 09:42:27 浏览: 19
当你想要爬取一个网页的内容时,可以使用Python编写一个简单的网页爬虫代码。以下是一个示例代码:
```python
import requests
# 发送HTTP请求获取网页内容
url = "http://example.com" # 替换为你要爬取的网页URL
response = requests.get(url)
content = response.text
# 解析网页内容
# 这里可以使用各种解析库,如BeautifulSoup、lxml等,来提取你需要的信息
# 示例:使用BeautifulSoup解析网页内容
from bs4 import BeautifulSoup
soup = BeautifulSoup(content, "html.parser")
# 这里可以根据网页的结构,使用相应的方法提取你需要的信息
# 示例:提取所有的链接
links = soup.find_all("a")
for link in links:
print(link.get("href"))
# 示例:提取网页标题
title = soup.title.string
print("网页标题:", title)
```
这段代码使用了`requests`库发送HTTP请求获取网页内容,并使用`BeautifulSoup`库解析网页内容。你可以根据自己的需求,使用不同的解析库和方法来提取你需要的信息。
相关问题
https://pvp.qq.com/web201605/herolist.shtml python爬虫英雌图片
好的,你可以使用Python的Requests和BeautifulSoup库来实现这个爬虫。以下是一个简单的例子代码,可以爬取英雄图片并保存到本地文件夹中:
```python
import requests
from bs4 import BeautifulSoup
# 发送网络请求,获取网页内容
url = 'https://pvp.qq.com/web201605/herolist.shtml'
res = requests.get(url)
# 使用BeautifulSoup解析网页内容
soup = BeautifulSoup(res.text, 'html.parser')
# 获取英雄图片链接
hero_imgs = soup.select('.herolist > li > a > img')
for hero_img in hero_imgs:
img_url = hero_img['src']
# 发送网络请求,下载图片并保存到本地
res = requests.get(img_url)
with open(hero_img['alt']+'.jpg', 'wb') as f:
f.write(res.content)
```
这个代码会将英雄图片下载到当前文件夹,并以英雄名字命名图片文件。你可以根据自己的需要修改代码,例如修改保存路径、图片格式等。
python天气爬虫代码
以下是一个简单的Python天气爬虫代码,可以获取指定城市的天气情况:
```python
import requests
from bs4 import BeautifulSoup
city = input("请输入城市名:")
url = f"http://www.weather.com.cn/weather/{city}.shtml"
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.encoding = 'utf-8'
soup = BeautifulSoup(response.text, 'html.parser')
weather_list = soup.select(".t .clearfix")
for weather in weather_list:
date = weather.select(".week")[0].text
weather_desc = weather.select(".wea")[0].text
temperature = weather.select(".tem")[0].text
print(date, weather_desc, temperature)
```
使用时只需要输入指定城市,即可输出该城市未来七天的天气情况。需要注意的是,该代码依赖于requests和BeautifulSoup库,请确保这两个库已经安装。