【发布时间】:2014-04-25 04:03:05
【问题描述】:
我正在尝试在 python 中使用 urllib2 模块来获取 url 的内容。
假设我的网址是“http://chortle.ccsu.edu/AssemblyTutorial/Chapter-01/ass01_12.html”
当我尝试使用这两条简单的行来获取它的内容时,它给了我完整的 html 内容。
response = urllib2.urlopen(url)
content = response.read()
print(content)
但是,当我在函数中重新定义这个东西时,它会返回一个没有 body 标记内容的 html。
def getContentURL(url):
''' returns the html content of the given url '''
response = urllib2.urlopen(url)
content = response.read()
return content
content = getContentURL(url)
soup = BeautifulSoup(conten) #added in edit
print(content)
我只得到这么多。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type"/>
<meta content="Bradley Kjell kjell at ieee dot org " name="author"/>
<meta content="2007" name="copyright"/>
<meta content="index,follow" name="robots"/>
<title>
CHAPTER 1 — Introduction
</title>
<link href="../AssemblyStyle.css" rel="stylesheet" type="text/css"/>
</head>
<body>
</body>
</html>
为什么会这样?我无法理解这种奇怪的行为。
================================编辑=============== ================================= 所以我用同样的东西写了一个test.py,它运行得很好。
import os
from bs4 import BeautifulSoup
import urllib2
import urllib
def getContentURL(url):
''' returns the content of the given url in text format '''
response = urllib2.urlopen(url)
content = response.read()
return content
url = "http://chortle.ccsu.edu/AssemblyTutorial/Chapter-01/ass01_1.html"
content = getContentURL(url)
soup = BeautifulSoup(content)
print(content) #prints everything
print(soup) #prints without the body's inner html
for link in soup.find_all('a'):
#print(link)
print(link.get('href'))
但是,我的原始代码中的相同代码行不起作用,一开始还有一些其他的东西。它的链接是https://github.com/kumar116/WebsiteCopier/blob/master/web_save.py。发布一个链接,因为它粘贴在这里。
你会看到的唯一变化是我正在打印 print(soup.prettify()) 或 print(soup)。
它吃掉了我身体标签内的所有东西。
我需要汤才能解析 html。
【问题讨论】:
-
你想做网页报废
-
我正在尝试获取此 html 的正文标记中的所有链接。所以,是的,网络抓取。我为此使用 BeautifulSoup。但只要我没有得到这个 html 中的所有内容,我就无法做到这一点。
-
检查你的函数名 getContent() 。它的错误调用。改变n尝试它的到来
-
@J.F.Sebastian Typo。已更正。我不使用任何名为 getContent() 的函数
-
edit 您的问题并将这些重要信息添加到其中。
print(content)之前将其传递给BeautifulSoup