gpt4 book ai didi

python - Selenium - 抓取动态生成的数据 Python

转载 作者:太空宇宙 更新时间:2023-11-03 17:03:00 24 4
gpt4 key购买 nike

我正在尝试从动态生成的网页获取数据。从我的搜索中,我发现 Selenium 可能是最好的选择,但我遇到了一些问题。我想要从中获取数据的网页是 this one我的测试搜索数据是“10403782”

到目前为止,我有以下源代码,能够找到搜索栏并进行搜索,但正如您所看到的,返回的结果是多个项目,我正在尝试找到没有小房子的项目左边变灰了。

# Initial connection and search
driver.get("http://firmaopslag.dk")
element = driver.find_element_by_id("firmanavn")
element.send_keys("10403782")
element.send_keys(Keys.RETURN)

# On search result page, find the result with the house
searchResults = driver.find_element_by_id("searchresult")

我认为定位蓝色房子的一种方法是查看颜色值,循环遍历所有结果项,找到房子颜色与灰色房子颜色不匹配的项。但是,每当我进行搜索(如上面的情况)时,searchResults 总是为空。我尝试按类名、id、标签进行搜索..似乎没有任何东西能够找到结果。本质上,正如我提到的,我想找到带有蓝色房子的结果并单击它。

编辑:我认为我最大的问题是,一旦搜索完成,我需要查看与初始页面不同的网页或不同的元素

对于最后一部分,一旦我进入正确的页面,我认为 beautifulsoup 是获取我感兴趣的数据的最佳方式,不是吗?

最佳答案

您可以检查style属性内的color:

# Initial connection and search
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Firefox()
driver.get("http://firmaopslag.dk")
element = driver.find_element_by_id("firmanavn")
element.send_keys("10403782")
element.send_keys(Keys.RETURN)

# wait for search results to appear
wait = WebDriverWait(driver, 10)
searchResults = wait.until(EC.presence_of_element_located((By.ID, "searchresult")))

for blue_house_result in searchResults.find_elements_by_xpath(".//button[.//span[contains(@class, 'glyphicon-home') and contains(@style, 'color: #002954;')]]"):
label = blue_house_result.find_element_by_tag_name("h4")
print(label.text)

请注意,我还添加了 wait以便在执行搜索后显示搜索结果。

Also for the final part, once I am on the correct page, I think beautifulsoup is the best way to get the data I am interested in, isn't it?

您可以使用 BeautifulSoup 进一步解析 driver.page_source 中的 HTML,但不一定需要它,因为您可以使用 selenium 定位元素>.

关于python - Selenium - 抓取动态生成的数据 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34865198/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com