我有一个简单的刮刀,我正在运行。我正在尝试从中搜索字母q的搜索结果山姆政府公司名称:
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 bs4 import BeautifulSoup
import re
import sys
reload(sys)
sys.setdefaultencoding('utf8')
letter = 'q'
driver = webdriver.PhantomJS()
driver.set_window_size(1120, 550)
driver.get("http://sam.gov")
#element = WebDriverWait(driver, 10).until(
# EC.presence_of_element_located((By.ID, "pbG220e071f_2de75f_2d417d_2d9c61_2d027d324c8fec:_viewRoot:j_id12:search1"))
# )
#element.click()
driver.find_element_by_id('pbG220e071f_2de75f_2d417d_2d9c61_2d027d324c8fec:_viewRoot:j_id12:search1').click()
driver.find_element_by_id(letter).send_keys(letter)
driver.find_element_by_id('RegSearchButton').click()
def crawl():
bsObj = BeautifulSoup(driver.page_source, "html.parser")
tableList = bsObj.find_all("table", {"class":"width100 menu_header_top_emr"})
tdList = bsObj.find_all("td", {"class":"menu_header width100"})
for table in tableList:
item = table.find_all("span", {"class":"results_body_text"})
print item[0].get_text().strip() + ', ' + item[1].get_text().strip()
if driver.find_element_by_id('anch_16'):
crawl()
driver.find_element_by_id('anch_16').click()
print "Going to next page"
else:
crawl()
print "Done with last page"
driver.quit()
当我运行它时,它会出现一个奇怪的错误,它困扰着我:
回溯(最近一次呼叫):
^{pr2}$此后,我尝试在初始化浏览器后立即使用隐式等待60。运气不好
我也试过webdriverwait(在下面的代码中注释掉了driver.get("http://sam.gov")
),它给了我一个TimeOutException。在
奇怪的是,如果我在get调用后立即执行print driver.page_source
,那么源代码就很好,它包含以下代码,其中实际上包含了具有我正在搜索的id的元素。也没有frame或iframe。在
<a id="pbG220e071f_2de75f_2d417d_2d9c61_2d027d324c8fec:_viewRoot:j_id12:search1" href="#" title="Search Records" onclick="if(typeof jsfcljs == 'function'){jsfcljs(document.getElementById('pbG220e071f_2de75f_2d417d_2d9c61_2d027d324c8fec:_viewRoot:j_id12'),{'pbG220e071f_2de75f_2d417d_2d9c61_2d027d324c8fec:_viewRoot:j_id12:search1':'pbG220e071f_2de75f_2d417d_2d9c61_2d027d324c8fec:_viewRoot:j_id12:search1'},'');}return false" class="button">
元素的Id定位器看起来像是动态生成的,您应该尝试其他定位器。在
您可以尝试使用
css_selector
作为以下:在或使用
^{pr2}$WebDriverWait
作为:-注意:-在查找元素之前,请确保它不在任何}
frame/iframe
内。如果它在任何frame/iframe
中,则需要在找到元素driver.switch_to_frame("frame/iframe id or name")
之前切换{相关问题 更多 >
编程相关推荐