【问题标题】:Scraping all tooltips in a website with Selenium(Python)?使用 Selenium(Python) 抓取网站中的所有工具提示?
【发布时间】:2018-04-20 10:22:03
【问题描述】:

我目前正在尝试抓取此网站 https://schedule.townsville-port.com.au/

我想抓取所有单独工具提示中的文本。

这是我必须悬停的典型元素的 html 的样子

<div event_id="55591" class="dhx_cal_event_line past_event" style="position:absolute; top:2px; height: 42px; left:1px; width:750px;"><div> 

这是工具提示的典型 html 的样子

<div class="dhtmlXTooltip tooltip" style="visibility: visible; left: 803px; bottom:74px;

我尝试了各种组合,例如尝试直接抓取工具提示,还尝试通过将鼠标悬停在需要悬停的位置来抓取 html。

tool_tips=driver.find_elements_by_class_name("dhx_cal_event_line past_event")

tool_tips=driver.find_elements_by_xpath("//div[@class=dhx_cal_event_line past_event]")

tool_tips=driver.find_element_by_css_selector("dhx_cal_event_line past_event")

我也尝试使用“dhtmlXTooltip tooltip”而不是“dhx_cal_event_line past_event”来使用相同的代码

我真的不明白为什么。

tool_tips=driver.find_elements_by_class_name("dhx_cal_event_line past_event")

没用。

Beautifulsoup 可以用来解决这个问题吗?由于 html 是动态的和变化的?

【问题讨论】:

  • 你需要实现ActionChainsfind_elements_by_class_name("dhx_cal_event_line past_event") 不起作用,因为不允许使用复合类名称。正确的 CSS 选择器也是 find_elements_by_css_selector(".dhx_cal_event_line.past_event")
  • 如果考虑到Beautifulsoup,你为什么不标记Beautifulsoup,但你已经标记了Selenium
  • 谢谢你我现在已经标记了它。
  • @Andersson 阅读了 ActionChains 的文档,看来我仍然需要找到元素,我该如何找到元素?我试过 find_elements_by_css_selector(".dhx_cal_event_line.past_event" 但也没有找到元素。我没有得到“没有这样的元素”异常。
  • 这是因为那些元素是动态生成的,所以还需要实现Wait

标签: python html selenium web-scraping beautifulsoup


【解决方案1】:

如果您在 Chrome DevTools 中打开“网络”选项卡并按 XHR 过滤,您可以看到该网站向http://schedule.townsville-port.com.au/spotschedule.php 发出请求。

from bs4 import BeautifulSoup
import requests

url = 'http://schedule.townsville-port.com.au/spotschedule.php'
r = requests.get(url, verify=False)
soup = BeautifulSoup(r.text, 'xml')

transports = {}
events = soup.find_all('event')

for e in events:
    transport_id = e['id']
    transport = {child.name: child.text for child in e.children}
    transports[transport_id] = transport

import pprint
pprint.pprint(transports)

输出:

{'48165': {'IMO': '8201480',
       'app_rec': 'Approved',
       'cargo': 'Passenger Vessel (Import)',
       'details': 'Inchcape Shipping Services Pty Limited',
       'duration': '8',
       'end_date': '2018-02-17 14:03:00.000',
       'sectionID': '10',
       'start_date': '2018-02-17 06:44:00.000',
       'text': 'ARTANIA',
       'visit_id': '19109'},
 ...
}

我发现摆脱SSLError 的唯一方法是使用verify=False 禁用证书验证,您可以阅读更多关于它的信息here

注意start_dateend_date 是UTC 时间,因此您可以指定timeshift 查询参数:

import time

utc_offset = -time.localtime().tm_gmtoff // 60  # in minutes    
url = f'http://schedule.townsville-port.com.au/spotschedule.php?timeshift={utc_offset}'

或转换日期并将它们存储为 datetime 对象(您可以阅读有关将时间从 UTC 转换为本地时区 here)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-08
    • 2019-10-31
    相关资源
    最近更新 更多