如何在python2中有选择地从表中删除数据

2024-04-26 22:36:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做一个我自己的小项目,并试图把我的想法围绕着网络报废。你知道吗

我正在使用python2和BeautifulSoap模块(但也尝试了其他模块,尝试了re模块和其他模块)。你知道吗

简单地说,考虑到网站:http://www.bankofcanada.ca/rates/exchange/daily-closing-past-five-day/我想收集有关每种货币汇率的信息,但要使用更灵活的代码。你知道吗

下面是我的例子:

import urllib2
from bs4 import BeautifulSoup
import string
import re

myurl = 'http://www.bankofcanada.ca/rates/exchange/daily-closing-past-five-day/'
soup  = BeautifulSoup(urllib2.urlopen(myurl).read(), "lxml")

dataTables = soup.find_all('td')

brandNewList = []

for x in dataTables:
    text = x.get_text().strip()
    brandNewList.append(text)
    #print  text

for index, item in enumerate(brandNewList):
    if item == "U.S. dollar (close)":
        for item in brandNewList[index:6]:
            print item

它显示:

$ python crawler.py
U.S. dollar (close)
1.4530
1.4557
1.4559
1.4490
1.4279

因此,正如您所看到的,我可以通过取消“td”标记来显示对应于每种货币的数据;如果将“th”与“td”标记结合使用,我可以得到更具体的数据。 但是,如果我真的不想指定确切的字符串“U.S.dollar(close)”,如何使脚本模式适应不同的网站呢? 例如,我只想输入终端的“US”/“US”作为参数,脚本将返回美元对应的值,这些值在不同网站上是如何命名的?你知道吗

另外,我是Python的初学者,所以你能告诉我重新编写网络爬虫的更简洁的方法吗?我觉得我是用一种“愚蠢”的方式写的,主要是:)


Tags: 模块textinimport网络rehttpfor
1条回答
网友
1楼 · 发布于 2024-04-26 22:36:24

how can I make the script mode adaptable to different websites?

不同的站点有不同的标记,在您的情况下,几乎不可能建立一个通用的、可靠的定位机制。根据你想要抓取多少个站点,你可以用一个EAFP approach循环不同的定位函数,直到你成功获得货币汇率。你知道吗

请注意,有些资源提供公共或私有api,您实际上不需要刮取它们。你知道吗

顺便说一下,您可以通过定位U.S. dollar (close)标签并获得following ^{} siblings来改进代码:

us_dollar_label = soup.find("td", text="U.S. dollar (close)")
rates = [td.get_text() for td in us_dollar_label.find_next_siblings("td")]

相关问题 更多 >