【问题标题】:For loop not working for XPATH in driver.find_element_by_xpath对于 driver.find_element_by_xpath 中的 XPATH,for 循环不起作用
【发布时间】:2020-12-12 07:13:55
【问题描述】:

我得到的输出只是第一列的第一行项目。 请让我知道问题是什么以及为什么 for 循环不适用于这段代码。

from selenium import webdriver
url="https://www.up-rera.in/frm_sanitize_prj_search.aspx?regid=918"
driver=webdriver.Chrome("/Users/prakhargarg/Desktop/chromedriver")
driver.get(url)
link = driver.find_element_by_link_text("Click Here To View Complete Project Details")
link.click()
window_after = driver.window_handles[1]
driver.switch_to.window(window_after)
driver.implicitly_wait(5)
rows=len(driver.find_elements_by_xpath('//*[@id="ShowTableApartment"]/tr'))
cols=len(driver.find_elements_by_xpath('//*[@id="ShowTableApartment"]/tr[1]/th'))
print(rows)
print(cols)
for r in range(2,rows+1):
    for c in range(1,cols+1):
        value=driver.find_element_by_xpath('//*[@id="ShowTableApartment"]/tr["+str(r)+"]/td["+str(c)+"]').text


print(value, end='   ')
driver.quit()

【问题讨论】:

    标签: python selenium-webdriver xpath web-scraping


    【解决方案1】:

    试试这个,这是我的代码:在此之前,您必须安装 pip install tabulate 和工作表。

    from selenium import webdriver
    from tabulate import tabulate
    
    url="https://www.up-rera.in/frm_sanitize_prj_search.aspx?regid=918"
    driver=webdriver.Chrome()
    driver.get(url)
    link = driver.find_element_by_link_text("Click Here To View Complete Project Details")
    link.click()
    window_after = driver.window_handles[1]
    driver.switch_to.window(window_after)
    driver.implicitly_wait(5)
    rows=len(driver.find_elements_by_xpath('//*[@id="ShowTableApartment"]/tr'))
    cols=len(driver.find_elements_by_xpath('//*[@id="ShowTableApartment"]/tr[1]/th'))
    rows=driver.find_elements_by_xpath('//*[@id="ShowTableApartment"]/tr')
    cols=driver.find_elements_by_xpath('//*[@id="ShowTableApartment"]/tr[1]/th')
    
    table = [[row.text.strip()] for row in rows]
    headers = [col.text for col in cols]
    
    print(tabulate(table, headers, tablefmt="pipe"))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-29
      • 2018-08-21
      • 1970-01-01
      • 2017-04-13
      • 2013-12-31
      • 2016-05-06
      • 1970-01-01
      • 2011-03-08
      相关资源
      最近更新 更多