【问题标题】:scraping yahoo stock news抓取雅虎股票新闻
【发布时间】:2020-07-11 10:38:12
【问题描述】:

我在页面末尾抓取与 Infosys 相关的新闻文章,但出现错误 selenium.common.exceptions.InvalidSelectorException:消息:无效选择器。 想抓取所有与Infosys相关的文章。

from bs4 import BeautifulSoup
import re
from selenium import webdriver
import chromedriver_binary
import string
import time
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By

driver = webdriver.Chrome("/Users/abhishekgupta/Downloads/chromedriver")
driver.get("https://finance.yahoo.com/quote/INFY/news?p=INFY")

for i in range(20): # adjust integer value for need
       # you can change right side number for scroll convenience or destination 
       driver.execute_script("window.scrollBy(0, 250)")
       # you can change time integer to float or remove
       time.sleep(1)

print(driver.find_element_by_xpath('//*[@id="latestQuoteNewsStream-0-Stream"]/ul/li[9]/div/div/div[2]/h3/a/text()').text())

【问题讨论】:

  • 你认为为什么会有li[9]?最好将所有li 作为列表,然后使用[-1] 从列表中获取最后一个元素
  • 第一个地址InvalidSelectorException 然后移动到抓取。请edit the question 将其限制为具有足够详细信息的特定问题,以确定适当的答案。避免一次问多个不同的问题。请参阅How to Ask 页面以获得澄清此问题的帮助。

标签: python selenium web-scraping


【解决方案1】:

页面中不存在您提供的xPath。

下载 xPath Finder Chrome 扩展程序以查找文章的正确 xPath。

这里是文章列表的xPath示例,需要循环遍历id:

/html/body/div[1]/div/div/div[1]/div/div[3]/div[1]/div/div[5]/div/div/div/ul/li[ID]/div/div/div[2]/h3/a/u

【讨论】:

    【解决方案2】:

    您可以使用// 而不是/div/div/div[2] 来使用不太详细的xpath

    如果您想要最后一项,则将所有li 获取为列表,然后使用[-1] 获取列表中的最后一个元素

    from selenium import webdriver
    import time
    
    driver = webdriver.Chrome("/Users/abhishekgupta/Downloads/chromedriver")
    #driver = webdriver.Firefox()
    
    driver.get("https://finance.yahoo.com/quote/INFY/news?p=INFY")
    
    for i in range(20):
           driver.execute_script("window.scrollBy(0, 250)")
           time.sleep(1)
    
    all_items = driver.find_elements_by_xpath('//*[@id="latestQuoteNewsStream-0-Stream"]/ul/li')
    
    #for item in all_items:
    #    print(item.find_element_by_xpath('.//h3/a').text)
    #    print(item.find_element_by_xpath('.//p').text)
    #    print('---')
        
    print(all_items[-1].find_element_by_xpath('.//h3/a').text)
    print(all_items[-1].find_element_by_xpath('.//p').text)
    

    【讨论】:

      【解决方案3】:

      我认为你的代码很好,只有一件事:在 selenium 中使用 xpath 与 scrapy 相比,或者如果你使用 lxml fromstring 库,我们检索文本或链接时几乎没有区别,所以这里有一些适合你的东西

      #use this code for printing instead 
      print(driver.find_element_by_xpath('//*[@id="latestQuoteNewsStream-0- Stream"]/ul/li[9]/div/div/div[2]/h3/a').text)
      

      即使你这样做,它也会以相同的方式工作,因为只有一个元素具有此 id,所以只需使用

      #This should also work fine
      print(driver.find_element_by_xpath('//*[@id="latestQuoteNewsStream-0- Stream"]').text)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-28
        • 2018-04-21
        相关资源
        最近更新 更多