简体   繁体   English

无法在 Python 中获取与 Selenium 的元素链接

[英]Can't get element link with Selenium in Python

I'm trying to click on the item but I can't seem to get the link from the element within this div.我正在尝试单击该项目,但似乎无法从此 div 中的元素获取链接。 I feel like I've tried everything.我觉得我什么都试过了。

Here's an example of the HTML code:这是 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>

Here is a couple ways I've tried to click:这是我尝试单击的几种方法:

#1 #1

item_div = item.find_element_by_tag_name('div')
item_link = item_div.find_element_by_tag_name('a')
#this returns NoElement for element with tag 'a'

#2 #2

item_link = item.find_element_by_css_selector('div.tile a')
#again, returns no element

I want to click on every item on a page using a for loop我想使用 for 循环单击页面上的每个项目

Here's the code so far:这是到目前为止的代码:

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.

I'm pretty new to selenium so I don't entirely understand why it can't find the element.我对 selenium 很陌生,所以我不完全明白为什么它找不到元素。 According to my code, I'm right on top of it..根据我的代码,我就在上面..

//div[@data-testid='product-tile']/a

A simple xpath to use to click.一个简单的 xpath 用于单击。

Now you either want to do this by grabbing all the a tags and using driver.get() or clicking each element.现在,您可以通过抓取所有 a 标签并使用 driver.get() 或单击每个元素来执行此操作。 If it goes to another page you'll be using driver.switchto another window and then driver.close().如果它转到另一个页面,您将使用 driver.switch 到另一个 window,然后是 driver.close()。 If it doesn't then you can just use driver.back() to repeatly grab the elements and then use it's index to click().如果没有,那么您可以使用 driver.back() 重复抓取元素,然后使用它的索引 click()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM