我在使用LXML抓取某些Web数据时遇到一些问题。我想使用BeautifulSoup从网站上抓取一件事,所以我决定使用LXML。我写了一些代码,让Discord Bot可以访问该网站。现在剩下的唯一事情就是编写代码来查找这些元素。这是我的代码,将不胜感激。
@tasks.loop(seconds = 10)
async def exchangeRate(self):
print("Loop Starting!")
HEADERS = {
'User-Agent' : "Magic Browser"
}
url = 'https://rubyrealms.com/economy/bank'
async with aiohttp.request("GET", url, headers=HEADERS) as response:
if response.status == 200:
#Scrap page content into one variable
content = await response.text()
#Initialize soup
soup = BeautifulSoup(content, "html.parser")
#Request access to site
page = requests.get(url)
#Declaring "tree" - Used to scrap by XPATH
tree = html.fromstring(page.content)
stuff = tree.xpath('//*[@id="content-wrap"]/div[3]/div[3]/div[2]/div[1]/div[2]/div[1]/div[2]/div[2]/h4')
print(stuff)
else:
print(f"The request was invalid\nStatus code: {response.status}")
这是我的Discord.Py ReWrite的任务循环,基本上每10秒钟它就会访问该站点。如图所示,下面的代码可以正常工作:
stuff = tree.xpath('//*[@id="content-wrap"]/div[3]/div[3]/div[2]/div[1]/div[2]/div[1]/div[2]/div[2]/h4')
print(stuff)
它唯一打印的是“循环启动!”从循环的开始。上面的代码(很长的代码)让我打印出来了:
Bot is ready for duty!
Exchange Cog is ready!
Waiting for loop!
Loop Starting!
[]
我想显示的是:
Bot is ready for duty!
Exchange Cog is ready!
Waiting for loop!
Loop Starting!
243
(该数字每天都在变化,这就是为什么我不能只使用一次。)
[如果有人知道我将如何解决这个问题,请提供帮助。预先谢谢你。
tree
具有7个<h4>
标签,它们符合您的注释中的描述。如果我对您的理解正确,那么为了获得全部7个,可以使用以下方法:
stuff = tree.xpath('//h4[@data-toggle="tooltip"]')
for s in stuff:
print(s.text)
输出为:
246
2
7
16
1
1
1
如果您提前知道目标号码(例如此246
中的tree
)始终是第一个,您甚至可以将其缩短为:
stuff = tree.xpath('//h4[@data-toggle="tooltip"]')[0]
print(stuff.text)
输出将是:
246