Python的基本Webscraping(美丽的汤和请求)

时间:2017-07-07 18:40:49

标签: python web-scraping beautifulsoup python-requests

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

#! 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')命令无法聚合下面定义的内容元素< a> inside class = r(在使用开发人员工具时可以看到一个仅用于Google搜索结果的类)。因此,我的浏览器中没有打开搜索结果的网页。

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

2 个答案:

答案 0 :(得分:1)

谷歌似乎发现你是一个机器人,而不是一个使用Cookie和Javascript的真实网络浏览器。他们似乎试图对新结果采取的措施仍然是让网络抓取工具跟随他们提供的链接并在其前面添加https://www.google.com,这样当您转到该网址时,他们仍然可以跟踪您的移动。 / p>

您还可以尝试在提供的链接中找到模式。例如,当您搜索' 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。当然,这不会影响它返回的第五个结果,因为它对谷歌网站来说是特别的。同样,在返回的每个URL的前面添加https://www.google.com可能是最安全的事情。

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

答案 1 :(得分:0)

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