如何使用seleniumpython逐个点击获取网站数据

2024-09-28 01:23:24 发布

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

我试图从网站上获取数据,但我想选择第一个1000链接打开一个接一个,从那里获取数据。你知道吗

我试过:

list_links = driver.find_elements_by_tag_name('a')

for i in list_links:
        print (i.get_attribute('href')) 

通过这个获得不需要的额外链接。你知道吗

例如:https://www.magicbricks.com/property-for-sale/residential-real-estate?bedroom=1,2,3,4,5,%3E5&proptype=Multistorey-Apartment,Builder-Floor-Apartment,Penthouse,Studio-Apartment,Residential-House,Villa,Residential-Plot&cityName=Mumbai

我们将获得超过5万个链接。如何打开只有前1000个链接有在下面与属性的照片。你知道吗

编辑

我也试过:

driver.find_elements_by_xpath("//div[@class='.l-srp__results.flex__item']")
driver.find_element_by_css_selector('a').get_attribute('href')

for matches in driver:
    print('Liking')
    print (matches)
    #matches.click()
    time.sleep(5)

但是获取错误:TypeError: 'WebDriver' object is not iterable

为什么我不能用这行链接:driver.find_element_by_css_selector('a').get_attribute('href')

编辑1

我试图排序链接如下,但得到错误

            result = re.findall(r'https://www.magicbricks.com/propertyDetails/', my_list)
            print (result)

错误:TypeError:应为类似字符串或字节的对象

或者尝试过

            a = ['https://www.magicbricks.com/propertyDetails/']
            output_names = [name for name in a if (name[:45] in my_list)]
            print (output_names)

什么也得不到。你知道吗

所有链接都在列表中。请建议

先谢谢你。请建议


Tags: nameinhttpsforgetby链接www
2条回答

我认为您应该收集列表中所有标记名为“a”且“href”属性不为空的元素。
然后遍历列表并逐个单击元素。
创建WebElement类型的列表并存储所有有效链接。
在这里,您可以应用更多的过滤器或条件,即链接包含一些字符或其他一些条件。

要在列表中存储WebElement,可以使用驱动程序.findEelements()此方法将返回WebElement类型的列表。你知道吗

硒不是一个好主意,网页刮。我建议您使用JMeter,它是免费的、开源的。你知道吗

http://www.testautomationguru.com/jmeter-how-to-do-web-scraping/

如果您想使用selenium,那么您尝试采用的方法并不是一种稳定的方法—单击并获取数据。相反,我建议你遵循这个-类似的东西在这里。这个例子是用java编写的。但你可以理解。你知道吗

driver.get("https://www.yahoo.com");

Map<Integer, List<String>> map = driver.findElements(By.xpath("//*[@href]")) 
                .stream()                             // find all elements which has href attribute & process one by one
                .map(ele -> ele.getAttribute("href")) // get the value of href
                .map(String::trim)                    // trim the text
                .distinct()                           // there could be duplicate links , so find unique
                .collect(Collectors.groupingBy(LinkUtil::getResponseCode)); // group the links based on the response code

更多信息在这里。你知道吗

http://www.testautomationguru.com/selenium-webdriver-how-to-find-broken-links-on-a-page/

相关问题 更多 >

    热门问题