使用 urllib 或 requests 爬取编程语言排行榜页面,并将其保存为 tiobe.html 格式。网址链接 https://www.tiobe.com/tiobe-index/
时间: 2023-06-12 17:06:48 浏览: 196
以下是使用 requests 库爬取并保存 tiobe.html 页面的代码:
```python
import requests
url = "https://www.tiobe.com/tiobe-index/"
response = requests.get(url)
with open("tiobe.html", "w", encoding="utf-8") as file:
file.write(response.text)
```
运行完毕后,会在当前目录下生成一个名为 tiobe.html 的文件,其中保存了网页的源代码。
相关问题
使用 urllib 或 requests 爬取编程语言排行榜页面
下面是使用 requests 库爬取编程语言排行榜页面的示例代码:
```python
import requests
url = 'https://www.tiobe.com/tiobe-index/'
response = requests.get(url)
if response.status_code == 200:
html = response.content.decode('utf-8')
print(html)
else:
print(f'Request failed with status code {response.status_code}')
```
该代码向 tiobe.com 发送一个 GET 请求,并从响应中获取页面的 HTML 内容。如果请求成功,则打印 HTML 内容;否则,打印失败信息。
请注意,我们需要对响应内容进行适当的解码,以便在控制台中正确显示页面内容。在上面的代码中,我们使用 utf-8 解码。如果网站的编码方式不同,则需要使用相应的编码方式进行解码。
利用urllib模块爬取https://m.huiyi8.com/fengjing/zuimei/网页中的图片
好的,以下是使用 Python 的 urllib 模块爬取图片的代码:
```python
import urllib.request
from bs4 import BeautifulSoup
url = 'https://m.huiyi8.com/fengjing/zuimei/'
response = urllib.request.urlopen(url)
html = response.read()
soup = BeautifulSoup(html, 'html.parser')
img_tags = soup.find_all('img')
for img in img_tags:
img_url = img.attrs.get('src')
if img_url and img_url.startswith('https://'):
filename = img_url.split('/')[-1]
urllib.request.urlretrieve(img_url, filename)
print(f"Downloaded {filename}")
```
解释一下代码:
1. 导入了 `urllib.request` 和 `BeautifulSoup` 模块。
2. 定义了要爬取的网页 URL。
3. 使用 `urllib.request.urlopen()` 函数获取网页 HTML 内容。
4. 使用 `BeautifulSoup` 解析网页 HTML。
5. 使用 `soup.find_all('img')` 获取所有图片标签。
6. 对于每个图片标签,使用 `img.attrs.get('src')` 获取图片 URL。
7. 如果图片 URL 以 `https://` 开头,则使用 `urllib.request.urlretrieve()` 函数下载图片。
8. 打印输出已下载的图片文件名。
请注意,在使用此代码时,需要先安装 `BeautifulSoup4` 和 `urllib` 模块。