Skip to main content
 首页 » 编程设计

Python:有什么方法可以在单页应用程序中进行网络抓取和检测更改

2024年11月24日10zlslch

所以我正在尝试进行网络抓取并检查网站中的特定更改,该网站有一个搜索栏,我需要在其中输入内容才能进入特定页面,其中我想网络抓取。问题是,该网站是一个单页应用程序,在使用新结果刷新页面后,URL 不会更改。我已经尝试使用 requests 但它没有被使用,因为它依赖于 URL...

requests 或 python 库中是否有方法可以绕过这个问题并让我继续我的想法?

请您参考如下方法:

我的建议是,尝试使用开发者控制台打开页面。输入数据时检查 SPA 发送的请求类型(XHR 请求是您感兴趣的)。 url地址有效负载格式等。然后模仿网页。使用 requests 创建一个 session 对象,获取页面(这可能不是强制性的,但它不会造成伤害,所以为什么不这样做)然后将有效负载发送到正确的地址,您将收到您的数据。可能它不会是 HTML 而更多是某种 JSON 数据,但这更好,因为以后更容易使用。如果您确实需要 HTML 版本,则可以在 python 中绑定(bind)到诸如 PhantomJS 之类的库。您可以使用它们来呈现页面,然后检查特定元素是否存在。您也可以使用 selenium 它是一个允许您控制浏览器的库。您甚至可以观看它的工作。它使用您现有的浏览器,因此它可以处理任何类型的网页 SPA 或其他。这完全取决于您的需求。如果您追求的是纯数据,如果您想模仿用户,我会选择我的第一个解决方案,那么 selenium 是迄今为止最简单的。

下面是 Selenium 的用法示例,来自他们的网站。

from selenium.common.exceptions import TimeoutException 
from selenium.webdriver.support.ui import WebDriverWait # available since 2.4.0 
from selenium.webdriver.support import expected_conditions as EC # available since 2.26.0 
 
# Create a new instance of the Firefox driver 
driver = webdriver.Firefox() 
 
# go to the google home page 
driver.get("http://www.google.com") 
 
# the page is ajaxy so the title is originally this: 
print driver.title 
 
# find the element that's name attribute is q (the google search box) 
inputElement = driver.find_element_by_name("q") 
 
# type in the search 
inputElement.send_keys("cheese!") 
 
# submit the form (although google automatically searches now without submitting) 
inputElement.submit() 
 
try: 
    # we have to wait for the page to refresh, the last thing that seems to be updated is the title 
    WebDriverWait(driver, 10).until(EC.title_contains("cheese!")) 
 
    # You should see "cheese! - Google Search" 
    print driver.title 
 
finally: 
    driver.quit()