我正在使用一个网站为机器人做一个爱情计算器模块。这是我的语法:
url = "https://www.lovecalculator.com/love.php?name1={}&name2={}".format(name1, name2)
async with aiohttp.get(url) as response:
soupObject = BeautifulSoup(await response.text(), "html.parser")
try:
description = soupObject.soup.find_all('div').find(class_='result score').get_text()
except:
description = 'Dr. Love is busy right now.'
如何正确从网站获取结果?我无法用我目前的语法做到这一点,我总是收到"Dr. Love现在很忙"的消息。这是页面源代码:http://prntscr.com/e4bnhg
我认为您可能会有一些语法错误。
-
soupObject
没有soup
属性 -
find_all
返回一个ResultSet
,应该在find
之前对其进行索引
尝试将soupObject.soup.find_all('div').find(class_='result score').get_text()
更改为soupObject.find_all('div')[0].find(class_='result score').get_text()
。
这是我的代码,它像一个魅力:
import urllib2
from bs4 import BeautifulSoup
name1, name2 = 'Alice', 'Bob'
url = 'https://www.lovecalculator.com/love.php?name1={}&name2={}'.format(name1, name2)
soup = BeautifulSoup(urllib2.urlopen(url).read(), 'html.parser')
love = soup.find('div', attrs={'class': 'result score'}).get_text().strip()
print(love)
结果是 54%