繁体   English   中英

使用Selenium和python抓取JavaScript生成的内容

[英]Issue scraping javascript generated content with Selenium and python

我正在尝试从该网站上抓取房地产数据: 示例如您所见,相关内容已放置在文章标签中。

我正在用phantomjs运行硒:

driver = webdriver.PhantomJS(executable_path=PJSpath)

然后,我在python中生成URL,因为所有搜索结果都是链接的一部分,因此我可以在程序中搜索所需内容,而无需填写表格。

致电之前

driver.get(engine_link)

我将engine_link复制到剪贴板,并且在chrome中可以正常打开。 接下来,我等待所有可能的重定向发生:

def wait_for_redirect(wdriver):
    elem = wdriver.find_element_by_tag_name("html")
    count = 0
    while True:
        count += 1
        if count > 5:
            print("Waited for redirect for 5 seconds!")
            return
        time.sleep(1)
        try:
            elem = wdriver.find_element_by_tag_name("html")
        except StaleElementReferenceException:
            return

现在,我最后要遍历当前页面上的所有<article>标签:

for article in driver.find_elements_by_tag_name("article"):

但是此循环从不返回任何内容。 该程序未找到任何文章标签,我已经使用xpath和CSS选择器对其进行了尝试。 此外,文章都包含在section标签中,该标签也找不到。

Selenium中这种特定类型的标签是否存在问题,或者我是否在这里缺少与JS相关的东西? 页面底部有一些JavaScript模板,其名称表明它们可以生成搜索结果。

任何帮助表示赞赏!

假装不是PhantomJS并添加“ 显式等待” (为我工作):

from selenium import webdriver
from selenium.webdriver import DesiredCapabilities
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# set a custom user-agent
user_agent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.57 Safari/537.36"
dcap = dict(DesiredCapabilities.PHANTOMJS)
dcap["phantomjs.page.settings.userAgent"] = user_agent

driver = webdriver.PhantomJS(desired_capabilities=dcap)
driver.get("http://www.seloger.com/list.htm?cp=40250&org=advanced_search&idtt=2&pxmin=50000&pxmax=200000&surfacemin=20&surfacemax=100&idtypebien=2&idtypebien=1&idtypebien=11")

# wait for arcitles to be present
wait = WebDriverWait(driver, 10)
wait.until(EC.presence_of_element_located((By.TAG_NAME, "article")))

# get articles
for article in driver.find_elements_by_tag_name("article"):
    print(article.text)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM