【问题标题】:getting data from certian website via python通过python从某个网站获取数据
【发布时间】:2021-12-02 09:46:05
【问题描述】:

我正在尝试从中国银行网站获取人民币对美元的汇率,但是我在尝试从网站中获取数据时迷失了方向,这是我的代码:

from lxml import etree
import requests

s = "https://www.boc.cn/sourcedb/whpj/enindex_1619.html"
page = requests.get(s)
tree = etree.HTML(page.text)
element = tree.xpath('./body/table[1]/tbody/tr/td[1]/table[1]/tbody/tr/td/table/tbody/tr[26]/td')
content = etree.tostring(element[0])

element 变量是我检查页面后该页面中美元行的位置 当我运行程序时,我收到以下消息:

文件“d:\Python\tebotCopy.py”,第 8 行,在 content = etree.tostring(element[0]) IndexError: list index out of range

【问题讨论】:

    标签: python html parsing python-requests screen-scraping


    【解决方案1】:

    您可以尝试不同的 XPath 来获取带有 USD 的行:

    import requests
    from lxml import etree
    
    s = "https://www.boc.cn/sourcedb/whpj/enindex_1619.html"
    page = requests.get(s)
    tree = etree.HTML(page.text)
    
    element = tree.xpath('//table[@bgcolor="#EAEAEA"]/tr[27]/td')
    for td in element:
        print(td.text, end=" ")
    print()
    

    打印:

    USD 641.51 636.29 644.23 644.23 646.12 2021.10.14 07:23:51  
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-05
      • 1970-01-01
      • 2020-11-15
      • 2012-03-27
      • 2018-05-23
      • 1970-01-01
      • 2011-01-02
      • 1970-01-01
      相关资源
      最近更新 更多