简体   繁体   English

使用 Selenium Python 单击表的所有链接

[英]Click all links of table using Selenium Python

In my project, I am downloading all the reports by clicking each link written as a "Date".在我的项目中,我通过单击每个写为“日期”的链接来下载所有报告。 Below is the image of the table.下面是桌子的图片。 要刮的表

I have to extract a report of each date mentioned in the table column "Payment Date".我必须提取表格列“付款日期”中提到的每个日期的报告。 Each date is a link for a report.每个日期都是报告的链接。 So, I am clicking all the dates one-by-one to get the report downloaded.因此,我逐一单击所有日期以下载报告。

for dt in driver.find_elements_by_xpath('//*[@id="tr-undefined"]/td[1]/span'):
    dt.click()
    time.sleep(random.randint(5, 10))

So, the process here going is when I click one date it will download a report of that date.因此,这里的过程是当我单击一个日期时,它将下载该日期的报告。 Then, I will click next date to get a report of that date.然后,我将单击下一个日期以获取该日期的报告。 So, I made a for loop to loop through all the links and get a report of all the dates.所以,我做了一个 for 循环来遍历所有链接并获得所有日期的报告。

But it is giving me Stale element exception.但它给了我陈旧的元素异常。 After clicking 1st date it is not able to click the next date.单击第一个日期后,将无法单击下一个日期。 I am getting error and code stops.我收到错误并且代码停止。

How can I solve this?我该如何解决这个问题?

You're getting a stale element exception because the DOM is updating elements in your selection on each click.您会收到一个陈旧的元素异常,因为 DOM 会在每次单击时更新您选择的元素。

An example: on-click , a tag "clicked" is appended to an element's class.一个例子: on-click ,一个标签"clicked"被附加到一个元素的类中。 Since the list you've selected contains elements which have changed (1st element has a new class), it throws an error.由于您选择的列表包含已更改的元素(第一个元素具有新类),因此会引发错误。

A quick and dirty solution is to re-perform your query after each iteration.一个快速而肮脏的解决方案是在每次迭代后重新执行查询。 This is especially helpful if the list of values grows or shrinks with clicks.如果值列表随着点击而增长或缩小,这将特别有用。

# Create an anonymous function to re-use
# This function can contain any selector
get_elements = lambda: driver.find_elements_by_xpath('//*[@id="tr-undefined"]/td[1]/span')

i = 0
while True:
    elements = get_elements()

    # Exit if you're finished iterating
    if not elements or i>len(elements):
        break
    
    # This should always work
    element[i].click()

    # sleep
    time.sleep(random.randint(5, 10))

    # Update your counter
    i+=1

The simplest way to solve it is to get a specific link each time before clicking on it.解决它的最简单方法是每次点击之前获取特定链接。

links = driver.find_elements_by_xpath('//*[@id="tr-undefined"]/td[1]/span')
for i in range(len(links)):
    element = driver.find_elements_by_xpath('(//*[@id="tr-undefined"]/td[1]/span)[i+1]')
    element.click()
    time.sleep(random.randint(5, 10))

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

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