我正在尝试从网站上抓取信息。到目前为止,我已经能够访问该网页,使用用户名和密码登录,然后根据需要将该登录页面的页面源打印到单独的 .html/.txt 文件中。
这就是问题出现的地方:在那个“登陆页面”上,有一个我想从中抓取数据的表格。如果我手动右键单击该表上的任何整数,然后选择“检查”,我会毫无问题地找到该整数。但是,当从整体上查看页面源时,我看不到整数 - 只是变量/参数名称。这让我相信它是一个动态网站。
我怎样才能抓取数据?
我一直在努力抓取这个网站,到目前为止,以下是可用技术对我的工作方式:
Chromium
包在我身上反复失败(在我的 Windows 7 笔记本电脑上),我什至发布了 question about the matter here .现在我会假设这只是一个失败的事业,但我愿意接受任何人的善意帮助。 Spynner
的描述看起来很有希望,但这种设置让我沮丧了很长一段时间 - 并且缺乏明确的介绍只会使像我这样的新手更加繁琐。 如果我的代码有任何用处,到目前为止,这是我如何使用
mechanize
:# Headless Browsing Using PhantomJS and Selenium
#
# PhantomJS is installed in current directory
#
from selenium import webdriver
import time
browser = webdriver.PhantomJS()
browser.set_window_size(1120, 550) # need a fake browser size to fetch elements
def login_entry(username, password):
login_email = browser.find_element_by_id('UserName')
login_email.send_keys(username)
login_password = browser.find_element_by_id('Password')
login_password.send_keys(password)
submit_elem = browser.find_element_by_xpath("//button[contains(text(), 'Log in')]")
submit_elem.click()
browser.get("https://www.example.com")
login_entry('usr_name', 'pwd')
time.sleep(10)
test_output = open('phantomjs_test_source_output.html', 'w')
test_output.write(repr(browser.page_source))
test_output.close()
browser.quit()
ps-如果有人认为我应该标记
javascript
对于这个问题,让我知道。我个人不知道 javascript,但我感觉到它可能是问题/解决方案的一部分。
最佳答案
尝试这样的事情。有时对于动态页面,您需要等待数据加载。
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
WebDriverWait(my_driver, my_time).until(EC.presence_of_all_elements_located(my_expected_element))
http://selenium-python.readthedocs.io/waits.html
https://seleniumhq.github.io/selenium/docs/api/py/webdriver_support/selenium.webdriver.support.expected_conditions.html
关于python - 通过 Python 脚本抓取动态网站 : how to get the values?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41968564/