【问题标题】:unable fetch date from youtube scrape selenium无法从 youtube 获取日期刮硒
【发布时间】:2021-06-22 04:35:04
【问题描述】:

这是我要获取的文本的屏幕截图:

检查元素的完整链接:-

https://www.youtube.com/watch?v=KwyVTQaBndU

我想从标签中获取 2021 年 6 月 21 日,请附上截图。

这是我试过的代码:

try:
    postdate = driver.find_element_by_xpath("//*[@id='container']//div[@id='info']//div[@id='date']").get_attribute(
        'innerText')
    print(postdate)
except Exception as e:
    print(e)

输出:

Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id='container']//div[@id='info']//div[@id='date']"}
  (Session info: chrome=91.0.4472.106)

它一直有效,但我猜 youtube 在格式上做了一些改变。所以它不起作用。

【问题讨论】:

  • 你试过完整的 X 路径吗?

标签: python-3.x selenium date selenium-webdriver web-scraping


【解决方案1】:

一个可靠的 CSS 选择器应该是:

span#dot+yt-formatted-string

我觉得有个错字,应该是innerHTML

像这样使用它:

try:
    postdate = driver.find_element_by_css_selector("span#dot+yt-formatted-string").get_attribute('innerHTML')
    print(postdate)
except Exception as e:
    print(e)

【讨论】:

  • 我有一个问题,比如我放的代码直到昨天都在工作,因为我每天都运行它,突然 youtube 对格式做了一些更改。所以它不起作用。我该如何克服它,或者无论如何我必须每次手动进行更改?
  • 查看这个定位器:- span#dot+yt-formatted-string - 我已经基于点编写了这个定位器,可以在视图和日期之间看到,所以将来他们删除点然后它会失败。但机会较少。但仍有可能
【解决方案2】:

您可以使用以下方式之一

X-path(你目前正在使用的)

postdate = driver.find_element_by_xpath('//*[@id="info-strings"]/yt-formatted-string').text
print(postdate)

完整的 X 路径

postdate = driver.find_element_by_xpath('/html/body/ytd-app/div/ytd-page-manager/ytd-watch-flexy/div[5]/div[1]/div/div[6]/div[2]/ytd-video-primary-info-renderer/div/div/div[1]/div[2]/yt-formatted-string').text
print(postdate)

CSS 选择器

postdate = driver.find_element_by_css_selector('#info-strings > yt-formatted-string').text
print(postdate)

还有一种方法

postdate = driver.find_element_by_xpath('//*[local-name()="yt-formatted-string" and @class="style-scope ytd-video-primary-info-renderer"]/parent::div/parent::div/parent::div')
print(postdate)

试试这些方法吧!

【讨论】:

  • 实际上我在提出问题之前已经尝试了所有方法,但没有一个起作用!得到像对象这样的错误是不可迭代的东西。
猜你喜欢
  • 2021-03-11
  • 1970-01-01
  • 1970-01-01
  • 2020-08-23
  • 2015-07-11
  • 1970-01-01
  • 1970-01-01
  • 2021-02-16
  • 2021-02-26
相关资源
最近更新 更多