如题先上代码:
import requests
import re
from bs4 import BeautifulSoup
import time
# 设置请求头
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'
}
# 遍历页面并爬取标题
for i in range(1, 101):
url = f'https://space.bilibili.com/{i}'
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')
title = soup.find('title').text
match = re.search(r'^(.*)的个人空间-.*$', title)
if match:
title = match.group(1)
print(f'{url}: {title}')
time.sleep(0.5)
这段程序实现了爬取某站用户个人主页的标题,其中包含了该用户的昵称和个人主页的描述。程序使用requests库发送HTTP GET请求获取页面内容,使用BeautifulSoup库解析HTML内容,然后使用正则表达式匹配标题中的昵称部分。如果找到了昵称,则输出格式为"{url}: {昵称}“,否则输出格式为”{url}: {完整标题}"。程序每次请求页面后会暂停0.5秒钟,以免对某站服务器造成过大的负载。循环次数为1到100,即爬取用户编号为1到100的个人主页。也可以更改里面的值,更改要爬取的数量