Как перейти по ссылке, используя Selenium и Python - PullRequest
1 голос
/ 10 апреля 2019

Привет. Я пытаюсь нажать на эту ссылку, используя селен, но она не нажимается

.

Это HTML с сайта

<td class=" sorting_1" data-key="title" data-label="Title"><a class="document-link" href="/view/html/inforce/current/act-1984-051?query=((Repealed%3DN+AND+PrintType%3D%22act.reprint%22+AND+PitValid%3D%40pointInTime(20190411000000))+OR+(Repealed%3DN+AND+PrintType%3D%22reprint%22+AND+PitValid%3D%40pointInTime(20190411000000)))+AND+Title%3D(%22Aboriginal+and+Torres+Strait+Islander+Communities+(Justice%2C+Land+and+Other+Matters)+Act+1984%22)&amp;dQuery=Document+Types%3D%22%3Cspan+class%3D'dq-highlight'%3EActs%3C%2Fspan%3E%2C+%3Cspan+class%3D'dq-highlight'%3ESL%3C%2Fspan%3E%22%2C+Search+In%3D%22%3Cspan+class%3D'dq-highlight'%3ETitle%3C%2Fspan%3E%22%2C+Exact+Phrase%3D%22%3Cspan+class%3D'dq-highlight'%3EAboriginal+and+Torres+Strait+Islander+Communities+(Justice%2C+Land+and+Other+Matters)+Act+1984%3C%2Fspan%3E%22%2C+Point+In+Time%3D%22%3Cspan+class%3D'dq-highlight'%3E11%2F04%2F2019%3C%2Fspan%3E%22">Aboriginal and Torres Strait Islander Communities (Justice, Land and Other Matters) Act 1984</a></td>

Это то, что я пытаюсь в моем коде

act_link = browser.find_element_by_xpath("//a[@class='document-link'][@href]").click()

Не могли бы вы проверить код и сообщить, что я делаю не так? Это полный код.

import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException
import csv
options = webdriver.ChromeOptions()
prefs = {'download.default_directory' : r'C:\Users\u0119342\Desktop\LEG_DOWNLOAD\Legislation@Koru\WORD\missing'}
options.add_experimental_option('prefs', prefs)
browser = webdriver.Chrome(executable_path=r'D:\CHROME\chromedriver.exe', chrome_options=options)
browser.get('https://www.legislation.qld.gov.au/')
for parameter in ['Aboriginal and Torres Strait Islander Communities (Justice, Land and Other Matters) Act 1984']:
    search_button = browser.find_element_by_xpath("//li/a[@href='/search/inforce']")
    search_button.click()
    search_field = browser.find_element_by_xpath("//div[@class='col-sm-8']/input[@type='text'][@class='form-control ui-autocomplete-input']")
    search_field.send_keys(parameter)
    search_in = browser.find_element_by_xpath("//select[@name='searchin']/option[@value='Title']")
    search_in.click()
    search_using = browser.find_element_by_xpath("//select[@name='searchusing']/option[@value='exactwords']")
    search_using.click()
    search_button1 = browser.find_element_by_xpath("//div [@class='col-sm-offset-2 col-sm-10']/button[@class='btn btn-primary btn-form']")
    search_button1.click()
    try:
        act_link = browser.find_element_by_xpath("//a[@class='document-link'][@href]").click()
    except NoSuchElementException:
        try:
            leg_his = browser.find_element_by_xpath("//a[@class='btn btn-default']/span[@id='glyphicon glyphicon-calendar']/span[@id='view-lh']")
            leg_his.click()
        except NoSuchElementException:
            try:    
                act_text = browser.find_element_by_xpath("//div[@id='lhview']/div[@class='content']")
                with open('output.rtf', 'w') as f:
                    f.write(act_text.text)
            except NoSuchElementException:
                time.sleep(10)
browser.back()
time.sleep(10)
browser.quit()

Я ожидаю, что ссылка тега href будет нажата и перейдет на следующую страницу.

Ответы [ 2 ]

1 голос
/ 11 апреля 2019

К click() на элементе с текстом Закон 1984 года об общинах аборигенов и жителей островов Торресова пролива (справедливость, земля и другие вопросы) вам необходимо ввести WebDriverWait для элемент, который можно нажимать , и вы можете использовать любую из следующих Стратегий локатора :

  • Использование LINK_TEXT:

    WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.LINK_TEXT, "Aboriginal and Torres Strait Islander Communities (Justice, Land and Other Matters) Act 1984"))).click()
    
  • Использование PARTIAL_LINK_TEXT:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.PARTIAL_LINK_TEXT, "Aboriginal and Torres Strait Islander Communities (Justice, Land and Other Matters) Act 1984"))).click()
    
  • Использование CSS_SELECTOR:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "td.sorting_1[data-key='title'][data-label='Title']>a.document-link[href^='/view/html/inforce/current/act-1984-051']"))).click()
    
  • Использование XPATH:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//td[@class=' sorting_1' and @data-key='title'][@data-label='Title']/a[@class='document-link' and starts-with(@href, '/view/html/inforce/current/act-1984-051')]"))).click()
    
  • Примечание : необходимо добавить следующий импорт:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    
0 голосов
/ 10 апреля 2019

Удалите [@href] из вашего Xpath, вам нужен Xpath для webElement, а не для атрибута webElement.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...