具有搜索和非动态URI的Python Web报废

时间:2019-01-24 03:00:14

标签: python python-3.x web-scraping beautifulsoup python-requests

我是python和web爬虫程序的初学者,我习惯于使用动态URL制作爬虫程序,当我在URL本身中输入特定参数时,URI会发生变化。
例如:维基百科。
(如果我输入了一个名为“ Stack Overflow”的搜索,那么我将获得一个类似https://en.wikipedia.org/wiki/Stack_Overflow的URI)

此刻,我面临开发一个网络收集器以从this page收集数据的挑战。

字段“ Texto / Termos a serem pesquisados” 对应一个搜索字段,但是当我输入搜索内容时,URL保持不变,不会让我得到正确的HTML代码来进行我的研究。 / p>

我过去经常与BeautifulSoup和Requests一起进行剪贴工作,但是在这种情况下它没有用,因为搜索后URL保持不变。

import requests
from bs4 import BeautifulSoup

url = 'http://comprasnet.gov.br/acesso.asp?url=/ConsultaLicitacoes/ConsLicitacao_texto.asp'
html = requests.get(url)
bs0bj = BeautifulSoup(html.content,'html.parser')

print(bsObj)
# And from now on i cant go any further  

通常我会做类似的事情

url = 'https://en.wikipedia.org/wiki/'
input = input('Input your search :)
search = url + input

然后完成所有BeautifulSoup事情,并执行findAll事情以从HTML代码获取我的数据。

我也尝试过使用Selenium,但是由于所有webdriver的原因,我正在寻找与之不同的东西。通过下面的代码,我已经取得了一些奇怪的结果,但是我仍然无法很好地抓取HTML。

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import requests
from bs4 import BeautifulSoup

# Acess the page and input the search on the field

driver = webdriver.Chrome()
driver.get('http://comprasnet.gov.br/acesso.asp?url=/ConsultaLicitacoes/ConsLicitacao_texto.asp')
driver.switch_to.frame('main2')
busca = driver.find_element_by_id("txtTermo")
busca.send_keys("GESTAO DE PESSOAS")
#data_inicio = driver.find_element_by_id('dt_publ_ini')
#data_inicio.send_keys("01/01/2018")
#data_fim = driver.find_element_by_id('dt_publ_fim')
#data_fim.send_keys('20/12/2018')
botao = driver.find_element_by_id('ok')
botao.click()

所有这些:
*有一种方法可以从这些静态网址中抓取数据吗?
*我可以通过代码在字段中输入搜索内容吗?
*为什么我不能抓取正确的源代码?

1 个答案:

答案 0 :(得分:0)

问题是您的初始搜索页面正在使用框架进行搜索和搜索结果,这使得BeautifulSoup难以使用它。我可以通过使用稍微不同的URL和MechanicalSoup来获得搜索结果:

>>> from mechanicalsoup import StatefulBrowser
>>> sb = StatefulBrowser()
>>> sb.open('http://comprasnet.gov.br/ConsultaLicitacoes/ConsLicitacao_texto.asp')
<Response [200]>
>>> sb.select_form()  # select the search form
<mechanicalsoup.form.Form object at 0x7f2c10b1bc18>
>>> sb['txtTermo'] = 'search text'  # input the text to search for
>>> sb.submit_selected()  # submit the form
<Response [200]>
>>> page = sb.get_current_page()  # get the returned page in BeautifulSoup form
>>> type(page)
<class 'bs4.BeautifulSoup'>

请注意,我在此处使用的URL是具有搜索表单的框架的URL,而不是您提供的内联URL的页面。这样会删除一层间接。

MechanicalSoup建立在BeautifulSoup之上,并提供了一些与网站进行交互的工具,类似于旧的mechanize库。