python - 如何让这个网络爬虫只打印歌曲的标题?
问题描述
import requests
from bs4 import BeautifulSoup
url = 'https://www.officialcharts.com/charts/singles-chart'
reqs = requests.get(url)
soup = BeautifulSoup(reqs.text, 'html.parser')
urls = []
for link in soup.find_all('a'):
print(link.get('href'))
def chart_spider(max_pages):
page = 1
while page >= max_pages:
url = "https://www.officialcharts.com/charts/singles-chart"
source_code = requests.get(url)
plain_text = source_code.text
soup = BeautifulSoup(plain_text, 'html.parser')
for link in soup.findAll('a', {"class": "title"}):
href = "BAD HABITS" + link.title(href)
print(href)
page += 1
chart_spider(1)
想知道如何只打印歌曲的标题而不是整个页面。我希望它通过前 100 名图表并打印所有标题。谢谢
解决方案
这是一个可能的解决方案,它尽可能少地修改您的代码:
#!/usr/bin/env python3
import requests
from bs4 import BeautifulSoup
URL = 'https://www.officialcharts.com/charts/singles-chart'
def chart_spider():
source_code = requests.get(URL)
plain_text = source_code.text
soup = BeautifulSoup(plain_text, 'html.parser')
for title in soup.find_all('div', {"class": "title"}):
print(title.contents[1].string)
chart_spider()
结果是在页面中找到的所有标题的列表,每行一个。
推荐阅读
- javascript - 全局正则表达式和数组
- opencv - VLC 可以连接 rtsp,但是 openCV 和 ffmpeg
- javascript - 传递给组件的对象变为空
- visual-studio - Visual Studio(不是 VS Code)可以进行远程 ssh 开发吗?文档说是的,但是
- linux - 如何在 bash 中解析这个 yaml 文件以获取特定值?
- react-native - 如何在 React Native Vector Icon 中选择同名的图标
- android - 无法使用 react-native 运行 android 模拟器(android-studio)
- python - Python中n个特征的梯度下降?吴恩达课程的一部分
- python - 在 Windows 上使用 Docker 创建 Lambda 层时遇到问题
- python - 在python中添加超链接到Excel csv文件