Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/296.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Can';t在Python中使用Selenium获取元素链接_Python_Selenium_Web Scraping_Bots_Nosuchelementexception - Fatal编程技术网

Can';t在Python中使用Selenium获取元素链接

Can';t在Python中使用Selenium获取元素链接,python,selenium,web-scraping,bots,nosuchelementexception,Python,Selenium,Web Scraping,Bots,Nosuchelementexception,我试图点击该项目,但我似乎无法从该分区中的元素获取链接。我觉得我已经尝试了所有方法 下面是HTML代码的一个示例: <div class="tile css-yrcab6-Tile e1yt6rrx0" data-testid="product-tile"> <a style="color:black" href="/product-name">...</a> #what I

我试图点击该项目,但我似乎无法从该分区中的元素获取链接。我觉得我已经尝试了所有方法

下面是HTML代码的一个示例:

<div class="tile css-yrcab6-Tile e1yt6rrx0" data-testid="product-tile">
  <a style="color:black" href="/product-name">...</a> #what I want to click
</div>
#二,

我想使用for循环单击页面上的每个项目

以下是迄今为止的代码:

def do_items(self):
    for page in range(self.maxPages):
        maincontent = driver.find_element_by_id('main-content')
        browsegrid = maincontent.find_element_by_class_name('browse-grid')
        items_on_page = browsegrid.find_elements_by_tag_name('div')
        for item in items_on_page:
            item_div = item.find_element_by_tag_name('div')
            item_link = item_div.find_element_by_tag_name('a')
            item_link.click()
            time.sleep(5)
            break
        break #breaks for the sake of testing, i only want to click the first item to see it works.
我对硒很陌生,所以我不完全理解它为什么找不到元素。根据我的密码,我就在上面

//div[@data-testid='product-tile']/a
用于单击的简单xpath


现在,您可以通过抓取所有a标记并使用driver.get()或单击每个元素来完成此操作。如果它转到另一个页面,您将使用driver.switch转到另一个窗口,然后使用driver.close()。如果没有,您可以使用driver.back()重复获取元素,然后使用它的索引单击()。

这很有效,谢谢!我想我把事情复杂化了。您使用“如果它转到另一个页面,您将使用driver.switch转到另一个窗口,然后使用driver.close()”是什么意思?当我单击元素时,它会将我带到我需要的页面,然后计划获取一些数据,返回,然后执行页面上的下一项(继续循环)。改用driver.switchto()有什么区别?如果它是作为一个新选项卡打开的,那么你必须做一些稍微不同的事情,以此类推。
def do_items(self):
    for page in range(self.maxPages):
        maincontent = driver.find_element_by_id('main-content')
        browsegrid = maincontent.find_element_by_class_name('browse-grid')
        items_on_page = browsegrid.find_elements_by_tag_name('div')
        for item in items_on_page:
            item_div = item.find_element_by_tag_name('div')
            item_link = item_div.find_element_by_tag_name('a')
            item_link.click()
            time.sleep(5)
            break
        break #breaks for the sake of testing, i only want to click the first item to see it works.
//div[@data-testid='product-tile']/a