Skip to main content
 首页 » 编程设计

python之带有python的Selenium webdriver抓取动态页面找不到元素

2024年10月24日38lyhabc

因此,关于 stackoverflow 上的动态内容抓取,有很多问题被问到,我仔细研究了所有这些问题,但建议的所有解决方案都不适用于以下问题:

上下文:

问题:

我无法访问此页面上的任何 DOM 元素。请注意,如果我能得到一些关于如何访问搜索栏和搜索按钮的提示,那将是一个很好的开始。 See page to scrape 我最终想要的是浏览地址列表、启动搜索并复制屏幕右侧显示的信息。

我尝试了以下方法:

  • 更改了 webdriver 的浏览器(从 Chrome 到 Firefox)
  • 增加了页面加载的等待时间

    try: 
        WebDriverWait(self.driver, 10).until(EC.presence_of_element_located((By.ID, "addressInput"))) 
    except: 
        print "address input not found" 
    
  • 尝试通过 ID、XPATH、NAME、TAG NAME 等访问该项目,但没有任何效果。

问题

  • 我还能尝试哪些我目前没有尝试过的(使用 Selenium webdriver)?
  • 有些网站真的无法抓取吗? (我不认为每次我重新加载页面时城市都使用算法生成任何随机 DOM)。

请您参考如下方法:

您可以使用此网址 http://50.17.237.182/PIM/ 获取源代码:

In [73]: from selenium import webdriver 
 
 
In [74]: dr = webdriver.PhantomJS() 
 
In [75]: dr.get("http://50.17.237.182/PIM/") 
 
In [76]: print(dr.find_element_by_id("addressInput")) 
<selenium.webdriver.remote.webelement.WebElement object at 0x7f4d21c80950> 

如果您查看返回的源,则有一个带有该 src url 的框架属性:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" 
   "http://www.w3.org/TR/html4/strict.dtd"> 
<html> 
 
<head> 
  <title>San Francisco Property Information Map </title> 
  <META name="description" content="Public access to useful property information and resources at the click of a mouse"><META name="keywords" content="san francisco, property, information, map, public, zoning, preservation, projects, permits, complaints, appeals"> 
</head> 
<frameset rows="100%,*" border="0"> 
  <frame src="http://50.17.237.182/PIM" frameborder="0" /> 
  <frame frameborder="0" noresize /> 
</frameset> 
 
<!-- pageok --> 
<!-- 02 --> 
<!-- --> 
</html> 

感谢@Alecxe,最简单的方法是使用dr.switch_to.frame(0):

In [77]: dr = webdriver.PhantomJS() 
 
In [78]: dr.get("http://propertymap.sfplanning.org/") 
 
In [79]:  dr.switch_to.frame(0)   
 
In [80]: print(dr.find_element_by_id("addressInput")) 
<selenium.webdriver.remote.webelement.WebElement object at 0x7f4d21c80190> 

如果您在浏览器中访问http://50.17.237.182/PIM/,您将看到与propertymap.sfplanning.org/完全相同的内容,唯一区别在于您可以使用前者完全访问元素。

如果你想输入一个值然后点击搜索框,它是这样的:

from selenium import webdriver 
 
 
dr = webdriver.PhantomJS() 
dr.get("http://propertymap.sfplanning.org/") 
 
dr.switch_to.frame(0) 
 
dr.find_element_by_id("addressInput").send_keys("whatever") 
dr.find_element_by_xpath("//input[@title='Search button']").click() 

但是如果你想提取数据,你可能会发现使用 url 进行查询是一个更简单的选择,你将从查询中得到一些 json。