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

时间:2019-07-13 14:49:13

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

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

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

1 个答案:

答案 0 :(得分:0)

如果您可以模拟浏览器用户的活动,则可以考虑安装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,您可以使用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模块以某种方式解决它,但是解决方案将更加复杂,尽管可能会更有效

相关问题