【问题标题】:Python crawler to get DOM info by using Selenium and PhantomJS使用 Selenium 和 PhantomJS 获取 DOM 信息的 Python 爬虫
【发布时间】:2016-12-12 05:55:11
【问题描述】:

我使用 SeleniumPhantomJS 希望从使用 javascript 构建 DOM 的网站获取数据。

下面的简单代码有效,但并不总是有效。我的意思是大多数时候它会返回一个没有执行 javascript 的空网站。它很少能得到我想要的正确信息。

from selenium import webdriver
from bs4 import BeautifulSoup

url = 'http://mall.pchome.com.tw/prod/QAAO6V-A9006XI59'
driver = webdriver.PhantomJS
driver.get(url)

print(driver.page_source, file=open('output.html','w'))

soup = BeautifulSoup(driver.page_source,"html5lib")
print(soup.select('#MetaDescription'))

返回空字符串的概率很高:

[<meta content="" id="MetaDescription" name="description"/>]

网站服务器是否不允许网络爬虫?我可以做些什么来修复我的代码?

更重要的是,我需要的所有信息都可以在 &lt;head&gt;&lt;meta&gt;tag 中找到。 (如上图所示,数据的 id 为 MetaDescription

或者有没有更简单的方法来获取&lt;head&gt;标签中的数据?

【问题讨论】:

  • soup.select('head')?不管怎样,你有没有试着等一下?

标签: javascript python python-3.x selenium phantomjs


【解决方案1】:

首先driver = webdriver.PhantomJS不是在Python中初始化一个selenium webdriver的正确方式,替换为:

driver = webdriver.PhantomJS()

您所描述的症状与您遇到时间问题时的症状相似。 Add a wait 等待所需元素出现在尝试获取页面源之前

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

driver = webdriver.PhantomJS()
driver.get(url)

# waiting for presence of an element
wait = WebDriverWait(driver, 10)
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "#MetaDescription")))

print(driver.page_source, file=open('output.html','w'))

driver.close()

# further HTML parsing here

您可能还需要ignore SSL errors and set the SSL protocol to any。在某些情况下,pretending not be PhantomJS 也有帮助。

【讨论】:

  • 谢谢!我没有考虑时间问题。但是,该页面在加载之前具有内容为空的标签。它使用javascript来填补空白。所以我用Implicit Waits代替了等待部分。我也尝试过同时使用这两个链接,成功了几次。
  • @WenT 好的,在这种情况下,只需选择正确的等待条件。例如,等待产品标题出现:#NickContainer。或者,可以等待产品img 元素出现..
  • 我使用了driver.implicitly_wait(30),但徒劳无功。但是,我尝试了time.sleep(5),它有效!!!所以它实际上是由时间问题引起的。但是implicitly waits 对我不起作用,我是否以错误的方式使用它?不管怎样,谢谢指点!!
  • @WenT time.sleep() 不是你应该使用的东西,它非常不可靠,而且大多数时候你最终会等待比你应该等待的时间更长。请继续为wait.until() 选择正确的条件,谢谢..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-09
  • 2020-12-18
  • 2013-06-06
相关资源
最近更新 更多