1

我正在做一个小项目,一个网站爬虫,我遇到了一个(我认为)与urllib.open(). 所以,假设我想抓取 Google 的主页、一个连接查询,然后是一个搜索查询。(我实际上并没有试图从谷歌上抓取,但我认为它们很容易展示。)

from bs4 import BeautifulSoup
import urllib

url = urllib.urlopen("https://www.google.com/")

soup = BeautifulSoup(url)

parseList1=[]

for i in soup.stripped_strings:
    parseList1.append(i)

parseList1 = list(parseList1[10:15])

#Second URL

url2 = urllib.urlopen("https://www.google.com/"+"#q=Kerbal Space Program")

soup2 = BeautifulSoup(url2)

parseList2=[]

for i in soup2.stripped_strings:
    parseList2.append(i)

parseList2 = list(parseList2[10:15])

#Third URL

url3 = urllib.urlopen("https://www.google.com/#q=Kerbal Space Program")

soup3 = BeautifulSoup(url3)

parseList3=[]

for i in soup3.stripped_strings:
    parseList3.append(i)

parseList3 = list(parseList3[10:15])

print " 1 "

for i in parseList1:
    print i

print " 2 "

for i in parseList2:
    print i

print " 3 "

for i in parseList3:
    print i

这打印出来:

1

A whole nasty mess of scraped code from Google

2

3

这让我相信 # 符号可能会阻止 URL 打开?连接的字符串不会引发任何连接错误,但仍然不会读入任何内容。

有谁知道为什么会发生这种情况?我从没想过字符串中的 # 会对代码产生任何影响。我认为这对我来说是一个愚蠢的错误,但如果是这样,我看不到它。

谢谢

4

1 回答 1

3

浏览器不应将 url 片段部分(以“#”结尾)发送到服务器。

RFC 1808(相对统一资源定位符):请注意,片段标识符(以及它前面的“#”)不被视为 URL 的一部分。但是,由于它通常与 URL 在相同的字符串上下文中使用,因此解析器必须能够在片段存在时识别它,并将其作为解析过程的一部分放在一边。

您可以在浏览器中获得正确的结果,因为浏览器向https://www.google.com发送请求,url 片段由 javascript 检测(这里与拼写检查类似,大多数网站不会这样做) ,然后浏览器发送一个新的ajax请求(https://www.google.com?q=xxxxx),最后用得到的json数据渲染页面。urllib 无法为您执行 javascript。

要解决您的问题,只需替换https://www.google.com/#q=Kerbal Space Programhttps://www.google.com/?q=Kerbal Space Program

于 2013-10-16T02:15:48.373 回答