Python и навигация по нескольким идентификаторам сеансов - PullRequest
0 голосов
/ 25 сентября 2019

** Я использую следующую ссылку "http://webapps.rrc.texas.gov/PR/publicQueriesMainAction.do", и я выполняю этот поиск: код оператора: 684474 в разделе" Производство оператором подачи ", и я нажал кнопку" в ожидании ", я использую округ как"Statewide" и месяц производства как "Jun", а год как "2019". Этот код возвращает меня туда, а также возвращает мне текущий URL (по какой-то причине на странице вывода не отображается полный URL, поэтому я вижу get print (driver).current_url) чтобы получить его: Начало исходного кода:

# First set of imports
import time
from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException
# Second set of imports
from bs4 import BeautifulSoup
import urllib.request as urllib2
import re
# Third set of imports (hashed out the second export since it is already included in the second set of exports)
import lxml.html
#import urllib.request as urllib2
import urllib.parse
# Fourth set of import, I need this to create an xml file
import requests
# Fifth set of exports
#from bs4 import BeautifulSoup (this would be a duplicate)
from urllib.request import urlopen,Request
from urllib.parse import urljoin,urlparse
# QEP Company code
Company_code = "684474"
# Chrome driver     
driver = webdriver.Chrome(executable_path=r'C:\Users\duane\python_work\TX_RRC_output\chromedriver.exe')
chrome_options = webdriver.ChromeOptions()
prefs = {'download.default_directory' : r"C:\Users\duane\python_work\TX_RRC_files_pending"}
chrome_options.add_experimental_option('prefs', prefs)
driver = webdriver.Chrome(chrome_options=chrome_options)
# Open tx rrc website page
driver.get('http://webapps.rrc.texas.gov/PR/publicQueriesMainAction.do')
# Enter operator code
elem = driver.find_element_by_name("operatorNo")
elem.send_keys(Company_code)
# Select oil and gas within the “Production by Filing Operator” section
allTextBoxes = driver.find_element_by_xpath("/html/body/table[4]/tbody/tr/td[3]/table/tbody/tr/td/form/table[2]/tbody/tr[3]/td[1]/input[4]")
allTextBoxes.click()
# Locate the District number (select statewide)
select_element_district = Select(driver.find_element_by_xpath("/html/body/table[4]/tbody/tr/td[3]/table/tbody/tr/td/form/table[2]/tbody/tr[3]/td[3]/select")).select_by_index(0)
# Locate the production year (2018 in this case), have to do years separately because the site allows a certain amount of queries per minute
select_element_productionyear = Select(driver.find_element_by_xpath("/html/body/table[4]/tbody/tr/td[3]/table/tbody/tr/td/form/table[2]/tbody/tr[3]/td[4]/select[2]")).select_by_index(1)
# Locate the production month
select_element_productionmonth = Select(driver.find_element_by_xpath("/html/body/table[4]/tbody/tr/td[3]/table/tbody/tr/td/form/table[2]/tbody/tr[3]/td[4]/select[1]")).select_by_index(7)
# Click the filing operator button
button_filingoperator = driver.find_element_by_xpath("/html/body/table[4]/tbody/tr/td[3]/table/tbody/tr/td/form/table[2]/tbody/tr[3]/td[5]/input")
button_filingoperator.click()
# this is how you select everything on a webpage
#elem_all = driver.find_element_by_css_selector('body')
#elem_all.send_keys(Keys.CONTROL + 'a')
#get_pdf = driver.find_element_by_xpath("/html/body/table[4]/tbody/tr[1]/td[3]/table/tbody/tr[2]/td/div/table/tbody/tr/td/table[2]/tbody/tr/td/table/tbody/tr[1]/td/table/tbody/tr/td/a")
#get_pdf.click()
print(driver.current_url) 

Конец исходного кода Я попытался добавить код в нижнюю часть этого кода, чтобы получить все ссылки в формате PDF, которые отображаются на странице вывода, иВот в чем проблема: я попытался добавить приведенный ниже код выше: Начало дополнительного кода:

url_new = driver.current_url
base_url = url_new
# fetch the page
res = urllib2.urlopen(base_url)
# parse the response into an xml tree
tree = lxml.html.fromstring(res.read())
# construct a namespace dictionary to pass to the xpath() call
# this lets us use regular expressions in the xpath
ns = {'re': 'http://exslt.org/regular-expressions'}
for node in tree.xpath('.//a[re:test(@href, "^/PR/viewPdfFormPublicAction.do?pdf=prForm&type=Pending&reportId=$", "i")]', namespaces=ns):
    # print the href, joining it to the base_url
    print(urllib.parse.urljoin(base_url, node.attrib['href']))

Окончание дополнительного кода Код работает нормально, но я не получаю вывод, я заметил, что если я беруURL-адрес, который будет меняться каждый раз, когда вы перезапускаете код и помещаете его в новый браузер, меня отправляют на страницу входа, как я могу загрузить все PDF-файлы со страницы вывода наиболееэффективно?Спасибо **

...