【发布时间】:2014-11-11 18:47:17
【问题描述】:
我已经浏览了相关问题,但我没有找到这个问题的答案:
我想打开一个 url 并解析它的内容。
当我在 google.com 上这样做时,没问题。
当我在没有文件名的 url 上执行此操作时,我经常被告知我读取了一个空字符串。
以下代码为例:
import urllib.request
#urls = ["http://www.google.com", "http://www.whoscored.com", "http://www.whoscored.com/LiveScores"]
#urls = ["http://www.whoscored.com", "http://www.whoscored.com/LiveScores"]
urls = ["http://www.whoscored.com/LiveScores"]
print("Type of urls: {0}.".format(str(type(urls))))
for url in urls:
print("\n\n\n\n---------------------------------------------\n\nUrl is: {0}.".format(url))
sock=urllib.request.urlopen(url)
print("I have this sock: {0}.".format(sock))
htmlSource = sock.read()
print("I read the source code...")
htmlSourceLine = sock.readlines()
sock.close()
htmlSourceString = str(htmlSource)
print("\n\nType of htmlSourceString: " + str(type(htmlSourceString)))
htmlSourceString = htmlSourceString.replace(">", ">\n")
htmlSourceString = htmlSourceString.replace("\\r\\n", "\n")
print(htmlSourceString)
print("\n\nI am done with this url: {0}.".format(url))
我不知道我有时会得到那个空字符串作为没有文件名的 url 的返回值——例如示例中的“www.whoscored.com/LiveScores”——而“google .com”或“www.whoscored.com”似乎一直有效。
我希望我的表述是可以理解的......
【问题讨论】:
-
Python 中有一些库,比如 BeautifulSoup 来解析内容。我不确定你想做什么
标签: python python-3.x web-scraping