【问题标题】:using beautiful soup for simulating a page-click to access all HTML on a page?使用漂亮的汤来模拟页面点击以访问页面上的所有 HTML?
【发布时间】:2019-01-07 01:00:25
【问题描述】:

我正在尝试抓取以下网站:

https://www.bandsintown.com/?came_from=257&sort_by_filter=Number+of+RSVPs

我能够使用 beautifulsoup 成功抓取页面上列出的事件,使用以下代码:

from bs4 import BeautifulSoup
import requests
url = 'https://www.bandsintown.com/?came_from=257&sort_by_filter=Number+of+RSVPs'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')


dates = soup.find_all('div', {'class': 'event-b58f7990'})
month=[]
day=[]
for i in dates:
    md = i.find_all('div')
    month.append(md[0].text)
    day.append(md[1].text)

但是,我遇到的问题是我只能抓取前 18 个事件 - 页面的其余部分只有在点击底部的“查看全部”按钮时才可用。有没有一种方法可以在 beautifulsoup 或其他方式中模拟单击此按钮,以便我可以抓取所有数据?我更喜欢将它保存在 python 中,因为我正在用 beautifulsoup 进行大部分抓取。非常感谢!

【问题讨论】:

  • 点击“查看全部”有什么作用?使用浏览器的检查器并观察“网络”选项卡以查看它请求的 URL,然后使用该 URL 进行抓取。仅供参考,该页面使用无限滚动(即向下滚动时通过 Ajax 请求新 URL),因此您应该使用适当的浏览器模拟器,例如 Selenium,或动态生成 URL(即通过在 URL 末尾添加 page=X 其中 X是你要抓取的页码)。
  • 好的。我认为你是对的 - 总而言之,滚动时可以加载 20 个页面:这是最后一个:bandsintown.com/… 我想知道我是否可以构建一个包含所有页面名称的对象,然后遍历并获取 div .

标签: python web-scraping beautifulsoup


【解决方案1】:

如果您可以计算出终点或在以下范围内设置终点(带有错误处理以防止过远),您可以获得 json 响应并解析出您需要的信息,如下所示。根据发出的请求数量,您可以选择重新使用会话连接。

import requests
import pandas as pd

url = 'https://www.bandsintown.com/upcomingEvents?came_from=257&sort_by_filter=Number+of+RSVPs&page={}&latitude=51.5167&longitude=0.0667'
results = []
for page in range(1,20):
    data = requests.get(url.format(page)).json()
    for item in data['events']:
        results.append([item['artistName'], item['eventDate']['day'],item['eventDate']['month']])
df = pd.DataFrame(results)
print(df)

【讨论】:

    猜你喜欢
    • 2021-09-20
    • 2012-12-07
    • 2012-08-01
    • 2017-08-15
    • 1970-01-01
    • 2012-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多