Selenium报废动态生成的数据Python

2024-04-26 21:43:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从动态生成的网页获取数据。从我的搜索中我发现硒可能是最好的选择,但我遇到了一些问题。我想从中获取数据的网页是 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,标签来搜索。。似乎没有什么东西能找到结果。基本上,正如我提到的,我想找到蓝色房子的结果,并点击它。在

编辑: 我认为我最大的问题是,一旦搜索完成,我需要寻找一个不同的网页或一个不同的元素,我已经从最初的网页

最后一部分,一旦我找到了正确的页面,我认为beauthulsoup是获得我感兴趣的数据的最佳方式,不是吗?在


Tags: the数据sendid网页searchbydriver
1条回答
网友
1楼 · 发布于 2024-04-26 21:43:19

您可以检查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定位元素。在

相关问题 更多 >