繁体   English   中英

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

[英]How to write a Python script to search for a keyword in a particular website's database using the website's search bar?

我想使用其搜索栏在特定网站中搜索关键字。 例如,我想在Wikipedia中搜索“鸟类”。 为此,我必须打开Goog​​le Chrome,然后打开Wikipedia,然后在Wikipidea的搜索引擎中搜索“ birds”一词。

我想使用Python自动执行此过程。 我正在使用PyCharm。

如果您可以模拟浏览器用户活动,则可以考虑安装Selenium和Chrome网络驱动程序(以下说明: 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,可使用el = browser.find_element_by_id("searchInput")进行选择,然后使用el.send_keys('birds' + Keys.RETURN)填充输入与您的请求和搜索。

因此脚本可能如下所示:

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模块以某种方式解决它,但是解决方案将更加复杂,尽管可能会更有效

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM