如何编写Python脚本来使用网站的搜索栏在特定网站的数据库中搜索关键字?

2024-10-04 01:30:42 发布

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

我想在一个特定的网站使用它的搜索栏搜索关键字。例如,我想在维基百科中搜索“小鸟”。为此,我必须打开googlechrome,然后打开Wikipedia,然后在Wikipidea的搜索引擎中搜索单词“birds”。在

我想用Python自动化这个过程。我用的是PyCharm。在


Tags: 网站过程关键字wikipedia单词pycharm搜索引擎birds
1条回答
网友
1楼 · 发布于 2024-10-04 01:30:42

如果模拟浏览器用户活动是可以的,您可以考虑安装Selenium和Chrome webdriver(下面是说明:https://pypi.org/project/selenium/)。 “例1”与问题的解决方案类似。在

搜索栏是<input type="search" name="search" placeholder="Search Wikipedia" title="Search Wikipedia [alt-shift-f]" accesskey="f" id="searchInput" tabindex="1" autocomplete="off">元素,有“searchInput”id,您可以使用这个id用el = browser.find_element_by_id("searchInput")选择它 {3>搜索并使用cd3}填充请求。在

因此,脚本可能如下所示:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

browser = webdriver.Chrome()

browser.get('https://en.wikipedia.org/wiki/Main_Page')

print("Enter a keyword to search on wikipedia: ", end='')
keyword = input()

elem = browser.find_element_by_id('searchInput')  # Find the search box
elem.send_keys(keyword + Keys.RETURN)

# do something with the opened page

browser.quit()

如果您不想分析浏览器活动,您可以使用requestsBeautifulSoup4模块来解决它,但是解决方案会更复杂,尽管可能更高效

相关问题 更多 >