【问题标题】:LXML XPATH - Data returned from one site and not anotherLXML XPATH - 从一个站点而不是另一个站点返回的数据
【发布时间】:2017-09-18 20:45:46
【问题描述】:

我刚刚学习 python,并决定玩一些网站抓取。

我创建了 1 个可以工作,而第二个,据我所知几乎相同,但不工作,我不知道为什么。

from lxml import html
import requests

page = requests.get('https://thronesdb.com/set/Core')
tree = html.fromstring(page.content)

cards = [tree.xpath('//a[@class = "card-tip"]/text()'),tree.xpath('//td[@data-th = "Faction"]/text()'),
              tree.xpath('//td[@data-th = "Cost"]/text()'),tree.xpath('//td[@data-th = "Type"]/text()'),
              tree.xpath('//td[@data-th = "STR"]/text()'),tree.xpath('//td[@data-th = "Traits"]/text()'),
              tree.xpath('//td[@data-th = "Set"]/text()'),tree.xpath('//a[@class = "card-tip"]/@data-code')]

print(cards)

那个符合我的预期(我知道它不漂亮)。它从网站上的表格中抓取某些元素。

这个返回[[]]

from lxml import html
import requests

page = requests.get('http://www.redflagdeals.com/search/#!/q=baby%20monitor')
tree = html.fromstring(page.content)

offers = [tree.xpath('//a[@class = "offer_title"]/text()')]

print(offers)

我期望它做的是给我一个列表,其中包含页面上每个 offer_title 元素的文本。

我从 Firebug 中获取的 xpath,即:

/html/body/div[1]/div/div/div/section/div[2]/ul[1]/li[2]/div/h3/a

这是来自网站的实际字符串:

<a href="/deal/other-kids-babies/angelcare-digital-video-and-sound-monitor-8999-9000-off-9724/" class="offer_title">Angelcare Digital Video And Sound Monitor - $89.99 ($90.00 Off)</a>

我还阅读了其他一些问题,但他们没有回答第一种方式是如何工作的,但不是第二种方式。由于新帐户的链接限制,无法发布它们。 标题:

  • Python - 无法使用 Beautiful 从网页表中检索数据 汤或 lxml xpath
  • Python lxml xpath 无输出
  • 使用 lxml / xpath() 从站点抓取文本时遇到问题

任何帮助将不胜感激。我在 lxml 网站上阅读了一些关于 xpath 的内容,但我在构建查询的方式中可能遗漏了一些东西。

谢谢!

【问题讨论】:

    标签: python html xpath lxml


    【解决方案1】:

    第一个代码起作用的原因是所需数据最初存在于DOM中,而在第二页上所需数据由JavaScript动态生成,因此您无法抓取它,因为requests不支持处理动态内容。

    您可以尝试使用例如Selenium + PhantomJS 来获取所需的数据,如下所示:

    from selenium import webdriver
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver.support.ui import WebDriverWait as wait
    
    driver = webdriver.PhantomJS(executable_path='/path/to/phantomJS')
    driver.get('http://www.redflagdeals.com/search/#!/q=baby%20monitor')
    xpath = '//a[@class = "offer_title"]'
    wait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, xpath)))
    offers = [link.get_attribute('textContent') for link in driver.find_elements_by_xpath(xpath)]
    

    【讨论】:

    • 感谢安德森!我担心答案会是超级技术性的,超出我的理解,但这是有道理的。我会试试 Selenium,看看我想出了什么。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-28
    相关资源
    最近更新 更多