【发布时间】:2015-10-16 23:43:00
【问题描述】:
我正在尝试编写一个简单的应用程序,它从网页中读取 HTML,将其转换为字符串,并将该字符串的某些片段显示给用户。 但是,这些切片似乎会改变自己!每次我运行我的代码时,我都会得到不同的输出!这是代码。
# import urllib so we can get HTML source
from urllib.request import urlopen
# import time, so we can choose which date to read from
import time
# save HTML to a variable
content = urlopen("http://www.islamicfinder.org/prayerDetail.php?country=canada&city=Toronto&state=ON&lang")
# make HTML readable and covert HTML to a string
content = str(content.read())
# select part of the string containing the prayer time table
table = content[24885:24935]
print(table) # print to test what is being selected
我不确定这里发生了什么。
【问题讨论】:
-
最好使用解析html并可以根据其属性提取特定元素(例如表格)的库。 Beautifulsoup 就是这样一种 Python 解析器。它可以在pypi.python.org/pypi/beautifulsoup4 获得,在stackoverflow.com/questions/11790535/… 有一个使用它进行表提取的示例。将它与islamicfinder.org/prayerDetail.php 一起使用会更加困难,因为视图源显示它没有为表分配类并且还嵌套它们,但它确实为所有 td 元素分配了相同的类。
标签: python html python-3.x urllib2 urllib