【发布时间】:2020-08-08 14:40:56
【问题描述】:
我在使用 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:
#Scrape 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 scrape 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
(这个数字每天都在变化,所以我不能只用一次。)
如果有人知道我将如何解决这个问题,请提供帮助。提前谢谢你。
【问题讨论】:
-
看起来 url 需要登录才能访问内容。我无法检查 xpath 是否准确或提供不同的解决方案。你能发布页面的html源代码和你正在查看的元素吗?
-
这里是网站的来源:pastebin.com/2PQsb5Sk 我想要得到的是:
246
-
您的问题中的表达式(“循环开始!”等)不在 html 中。
-
循环开始就在那里,所以我知道循环开始了。
-
部件:机器人已准备就绪!交换齿轮已准备就绪!等待循环!循环开始!不在 HTML 中,因为它们是加载我的不和谐机器人的一部分。
标签: python web-scraping beautifulsoup lxml