【问题标题】:BeautifulSoup Div Class returns emptyBeautifulSoup Div 类返回空
【发布时间】:2018-05-24 01:59:27
【问题描述】:

我检查了类似的问题,但找不到解决方案...

我正在尝试从以下页面中获取额外旅行时间 (46) 的分钟数:https://www.tomtom.com/en_gb/trafficindex/city/istanbul

我尝试了 2 种方法(Xpath 和查找类),但都返回空。

import requests
from bs4 import BeautifulSoup
from lxml.html import fromstring

page = requests.get("https://www.tomtom.com/en_gb/trafficindex/city/istanbul")
tree = fromstring(page.content)

soup = BeautifulSoup(page.content, 'html.parser')



#print([type(item) for item in list(soup.children)])

html = list(soup.children)[2]

g_data = soup.find_all("div", {"class_": "big.ng-binding"})

congestion = tree.xpath("/html/body/div/div[2]/div[2]/div[2]/section[2]/div/div[2]/div/div[2]/div/div[2]/div[1]/div[1]/text()")
print(congestion)
print(len(g_data))

我是否遗漏了一些明显的东西?

非常感谢您的帮助!

【问题讨论】:

  • 您要搜索的课程似乎在您要查找的页面上不存在。您可能还想阅读this entry...

标签: string python-3.x class beautifulsoup


【解决方案1】:

不幸的是,仅BeautifulSoup 不足以完成它。该网站使用 JavaScript 生成内容,因此您必须使用其他工具,例如 Selenium

import bs4 as bs
import re
from selenium import webdriver

url = 'https://www.tomtom.com/en_gb/trafficindex/city/istanbul'

driver = webdriver.Firefox()
driver.get(url)           
html = driver.page_source
soup = bs.BeautifulSoup(html)

我可以看到两种提取额外时间的方法:

1.寻找divclass="text-big ng-binding"

div = soup.find_all('div', attrs={'class' : 'text-big ng-binding'})
result = div[0].text

2.先查找包含Per day文本的div,然后向上查找两个div

div = soup.find_all(text=re.compile('Per day'))
result = div.find_previous('div').find_previous('div').text

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-24
    • 2021-07-21
    • 1970-01-01
    • 2019-12-12
    • 2019-03-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多