【问题标题】:Why can't this class be found with this CSS selector?为什么这个 CSS 选择器找不到这个类?
【发布时间】:2019-12-26 11:52:53
【问题描述】:

我正在尝试使用 xpath 快捷方式或 css 选择器来查找页面上适合此的所有对象:

<span class="perWord ng-binding">$0.20</span>

我很难理解选择器,但我尝试过:

(Pdb) selector.css('.perWord').getall()
[]
(Pdb) selector.css('.perWord')
[]
(Pdb) selector.css('perWord')
[]
(Pdb) selector.css('ng-binding')
[]
(Pdb) selector.css('perWord ng-binding')
[]
(Pdb) selector.css('.perWord_ng-binding')
[]
(Pdb) selector.css('.ng-binding').getall()
['<title ng-bind-template="100 Days In Appalachia | Who Pays Writers? " class="ng-binding">100 Days In Appalachia | Who Pays Writers? </title>', '<div ng-bind="venue.name" class="pull-left ng-binding">100 Days In Appalachia</div>', '<div class="pull-right small grayLighter ng-binding"> report<span ng-bind="GrammarHelper.pluralS(interactions.length)" class="ng-binding"></span> </div>', '<span ng-bind="GrammarHelper.pluralS(interactions.length)" class="ng-binding"></span>']

这是我正在使用的网站和代码:

driver = webdriver.Chrome()
driver.get('http://whopayswriters.com/#/publication/100-days-in-appalachia')
selector = Selector(text = driver.page_source)
pdb.set_trace()

我希望给出页面上出现的所有五个实例:

<span class="perWord ng-binding">$0.20</span>

【问题讨论】:

  • 内容是动态加载的

标签: python xpath beautifulsoup scrapy css-selectors


【解决方案1】:

使用 selenium 为我成功:

from selenium import webdriver
import time

driver = webdriver.Chrome('chromedriver.exe')
driver.get('http://whopayswriters.com/#/publication/100-days-in-appalachia')
time.sleep(3)
elems = driver.find_elements_by_class_name("perWord")

如果你想尝试在你的代码中添加time.sleep(3),因为有时页面还没有加载,所以找不到元素。

【讨论】:

  • 嗯,我刚试过,它也适用于我。你知道为什么 scrappy 选择器不起作用吗?
  • @DavidHampton 该网页使用 JS 并且某些内容是异步加载的,因此scrapy 的请求在加载所有内容并且所需的元素不存在之前获取初始内容。希望我能帮上忙。
【解决方案2】:

尝试在代码中使用WebDriverWaitsleep 以增加特定请求的加载时间。

此外,它是一个动态请求,因此页面源中不存在任何元素。因此,scrapy 选择器不会在响应中找到元素。您应该使用一些处理动态请求的方法,例如selenium, splash

【讨论】:

    【解决方案3】:

    该数据是从返回 json 的 xhr 调用动态添加的。单独使用requests 就足够了。您可以计算返回的 json 的每个单词。呼叫可以在网络选项卡中找到。如果您需要能够链接回来,您可以从 json 添加 id。

    import requests
    
    r = requests.get('http://whopayswriters.com/reports/public?design=cf&view=interaction_venues&key=%22f6c531bac691fa7846cb0b0c4b081a08%22&reduce=false&include_docs=true').json()
    per_word = ['$' + str(round(int(i['doc']['compensation']['Stipend / Honoraria / Fee'].replace('$',''))/i['doc']['pieceLength'],2)) for i in r['rows']]
    print(per_word)
    

    例如,您可以链接到特征长度:

    per_word = {i['doc']['pieceLength']:'$' + str(round(int(i['doc']['compensation']['Stipend / Honoraria / Fee'].replace('$',''))/i['doc']['pieceLength'],2)) for i in r['rows']}
    print(per_word)
    

    【讨论】:

      猜你喜欢
      • 2012-04-07
      • 1970-01-01
      • 2011-01-18
      • 2011-06-30
      • 1970-01-01
      • 1970-01-01
      • 2012-11-16
      • 1970-01-01
      • 2013-09-08
      相关资源
      最近更新 更多