Home > Mobile >  getting data from certian website via python
getting data from certian website via python

Time:10-16

I'm trying to get the Chinese Yuan exchange rate to USD from the Bank of China website, however I'm lost in trying to get the data out of the website, here is my code:

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])

the element variable is where the USD line in that page after I inspected the page when I run the program I get this message:

File "d:\Python\tebotCopy.py", line 8, in content = etree.tostring(element[0]) IndexError: list index out of range

CodePudding user response:

You can try different XPath to get row with 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()

Prints:

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