【发布时间】:2018-11-26 13:49:54
【问题描述】:
我正在尝试使用 python 和 beautifulsoup 抓取谷歌搜索结果。在我的第一个程序中,我只是想获取搜索结果页面上的所有链接。最终我想做的是跟随其他网站的链接,然后抓取这些网站。问题是当我查看程序给我的链接时,它们没有指向正确的 url。例如,在 google 中搜索“what is python”后的第一个网站 url 是 'https://www.python.org/doc/essays/blurb/' 但是我的程序给了我 '/url?q=https://www.python.org/doc/essays/blurb/&sa=U&ved=0ahUKEwirv7mZzNnbAhXD5YMKHdl0AFsQFggUMAA&usg=AOvVaw3Q2RD0gl-X3BiEJ-5HIxmF'
查看 BeautifulSoup 文档,我期望输出类似于他们的示例:
for link in soup.find_all('a'):
print(link.get('href'))
# http://example.com/elsie
# http://example.com/lacie
# http://example.com/tillie
相反,我在网站地址之后得到了一个前面的“/url?q=”和许多意想不到的字符。有人可以解释为什么我没有得到预期的输出吗? 这是我的代码:
import requests
from bs4 import BeautifulSoup
search_item = 'what is python'
url = "https://www.google.ca/search?q=" + search_item
response = requests.get(url)
soup = BeautifulSoup(response.text, "lxml")
for link in soup.find_all('a'):
print(link.get('href'))
【问题讨论】:
-
谢谢,我想这可能是我的解决方案。但是谁能解释为什么我没有得到预期的输出?例如查看 beautifulsoup 文档,我期待与此类似的输出: for link in soup.find_all('a'): print(link.get('href')) # example.com/elsie # example.com/lacie # @987654326 @
标签: python web-scraping beautifulsoup