Python的基本Web Scraping(Beautifulsoup和Requests)

问题描述 投票:0回答:2

所以我一直在使用Al Sweigart的在线Automate The Boring Stuff With Python教程,我刚刚进入了webscraping部分。这是我的代码,描述了程序应该做什么:

#! python3
# lucky.py - A small program that allows you to get search keywords from
# command line arguments, retrieve the search results page, and open
# a new browser tab for each result

# Steps:
# 1. Read the command line arguments from sys.argv
# 2. Fetch the search result page with the requests module
# 3. Find the links to each search result
# 4. Call the webbrowser.open() function to open the web browser

import sys, requests, bs4, webbrowser

# 1. Read the command line arguments from sys.argv

print('Googling...')

if len(sys.argv) > 1:
    search = ' '.join(sys.argv[1:])

url = "https://www.google.com/#q="

for i in range(len(search.split())):
    url += search.split()[i] + "+"

# 2. Fetch the search result page with the requests module

page = requests.get(url)

# 3. Find the links to each search result

soup = bs4.BeautifulSoup(page.text, 'lxml')
linkElems = soup.select('.r a')

# 4. Call the webbrowser.open() function to open the web browser

numOpen = min(5, len(linkElems))
for i in range(numOpen):
    webbrowser.open("http://google.com" + linkElems[i].get('href'))

所以这里的问题是当我检查linkElems的长度时,它为0,这意味着soup.select('。r a')命令无法聚合在class = r内的元素<a>下定义的内容(仅限一个类)用于Google中的搜索结果,使用开发者工具时可以看到)。因此,我的浏览器中没有打开搜索结果的网页。

我认为这个问题可能与HTML解析器无法正常工作有关,或谷歌改变其HTML代码的工作方式(?)。任何洞察这个问题将不胜感激!

python web-scraping beautifulsoup python-requests
2个回答
1
投票

谷歌似乎发现你是一个机器人,而不是一个真正的使用Cookie和Javascript的网络浏览器。他们似乎试图用新结果做的仍然是让网络抓取者按照他们提供的链接并在其前面加上https://www.google.com,这样当你转到那个URL时,他们仍然可以跟踪你的动作。

您还可以尝试在提供的链接中找到模式。例如,当您搜索“linux”时,它会返回以下内容:

/url?q=https://en.wikipedia.org/wiki/Linux&sa=U&ved=9775308e-206b-11e8-b45f-fb72cae612a8&usg=9775308e-206b-11e8-b45f-fb72cae612a8
/url?q=https://www.linux.org/&sa=U&ved=9775308e-206b-11e8-b45f-fb72cae612a8&usg=9775308e-206b-11e8-b45f-fb72cae612a8
/url?q=https://www.linux.com/what-is-linux&sa=U&ved=9775308e-206b-11e8-b45f-fb72cae612a8&usg=d50ea51a-206b-11e8-9432-2bee635f8337
/url?q=https://www.ubuntu.com/&sa=U&ved=9775308e-206b-11e8-b45f-fb72cae612a8&usg=dab9f6a4-206b-11e8-a999-3fc9d4576425
/search?q=linux&ie=UTF-8&prmd=ivns&source=univ&tbm=nws&tbo=u&sa=X&ved=9775308e-206b-11e8-b45f-fb72cae612a8

您可以使用正则表达式来抓取'/ url?q ='和'&sa = U&ved ='之间的部分,因为这是您可能想要的URL。当然,这与它返回的第5个结果无效,因为它对谷歌网站来说是特别的。再一次,可能在返回的每个URL的前面添加https://www.google.com是最安全的事情。

大多数搜索引擎(甚至是duckduckgo.com)都试图跟踪搜索结果和点击次数。如果你试图避免它,他们会有检测代码阻止你。您可能已经遇到过这种情况,谷歌告诉您他们已经从您的IP中检测到大量搜索,您必须通过验证码测试才能继续。


0
投票

linkElems = soup.find_all('a',href=True)这将返回所有相关的<a>标签,您可以处理列表以确定要保留的内容和不保留的内容。

© www.soinside.com 2019 - 2024. All rights reserved.