使用搜索和非动态URI的Python Web废弃

2024-04-18 22:02:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python和web scrapers世界的乞丐,我习惯用动态URL创建scrapers,当我在URL中输入特定参数时,URI会发生变化。
例如:维基百科。
(如果我输入一个名为“Stack Overflow”的搜索,我的URI如下:https://en.wikipedia.org/wiki/Stack_Overflow

当时,我被要求开发一个web scraper来从this page收集数据。你知道吗

字段“Texto/Termos a serem pesquisados”对应于一个搜索字段,但是当我输入搜索时,URL保持不变,不允许我为我的研究获得正确的HTML代码。你知道吗

我习惯于使用BeautifulSoup并请求执行报废操作,但在本例中它没有任何用处,因为在搜索之后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

然后做所有漂亮的事情,最后从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()

考虑到这些:
*有没有办法从这些静态URL中删除数据?
*我可以通过代码在字段中输入搜索吗?
*为什么我不能刮去正确的源代码?你知道吗


Tags: 代码fromimportidurlinputbydriver
1条回答
网友
1楼 · 发布于 2024-04-18 22:02:18

问题是,您的初始搜索页面使用了搜索结果框架,这使得BeautifulSoup很难使用它。我可以通过使用稍微不同的URL和^{}来获得搜索结果:

>>> 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,而不是您提供的内联表单的页面。这就消除了一层间接性。你知道吗

MechanicalSoup构建在BeautifulSoup之上,提供了一些与网站交互的工具,与旧的mechanize库类似。你知道吗

相关问题 更多 >