【问题标题】:Using urllib with Python 3在 Python 3 中使用 urllib
【发布时间】: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

我不确定这里发生了什么。

【问题讨论】:

标签: python html python-3.x urllib2 urllib


【解决方案1】:

您不应该通过抓取列表的特定索引来寻找您想要的部分,网站通常是动态的,并且列表每次都包含完全相同的内容

你要做的是搜索你想要的表格,所以说表格以关键字class="prayer_table"开头,你可以用str.find()找到这个

更好的是,从网页中提取表格而不是依赖str.find() 下面的代码来自关于从网页中提取表格reference 的问题

from lxml import etree
import urllib

web = urllib.urlopen("http://www.ffiec.gov/census/report.aspx?year=2011&state=01&report=demographic&msa=11500")
s = web.read()

html = etree.HTML(s)

## Get all 'tr'
tr_nodes = html.xpath('//table[@id="Report1_dgReportDemographic"]/tr')

## 'th' is inside first 'tr'
header = [i[0].text for i in tr_nodes[0].xpath("th")]

## Get text from rest all 'tr'
td_content = [[td.text for td in tr.xpath('td')] for tr in tr_nodes[1:]]

【讨论】:

    【解决方案2】:

    你真的应该使用美丽汤之类的东西。以下内容应该会有所帮助。通过查看该 url 的源代码,该表没有 id/class,这使得查找变得更加棘手。

    from bs4 import BeautifulSoup
    import requests
    
    url = "http://www.islamicfinder.org/prayerDetail.php?country=canada&city=Toronto&state=ON&lang"
    r = requests.get(url)
    soup = BeautifulSoup(r.text)
    
    for table in soup.find_all('table'):
        # here you can find the table you want and deal with the results
        print(table)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-02-14
      • 1970-01-01
      • 2012-09-25
      • 2016-07-28
      • 2014-09-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多