我正在抓捕该网站https://robertsspaceindustries.com/pledge/ship-upgrades?to-ship=173,我想在“选择您的船”文本的右侧获得“箭头”文本
我尝试使用请求和BeautifulSoup选择包含文本的标签,当我检查页面时,我可以看到文本在标签之间的位置,我尝试使用soup.select(“。name”)选择它仍然会得到空字符串,可能是数据是用Javascript渲染的,所以我尝试了selenium并尝试等待元素加载后再选择它,这仍然不是我的代码
try:
element = WebDriverWait(driver, 20).until(
EC.presence_of_element_located((By.CLASS_NAME, "name"))
)
select_tags = driver.find_elements_by_css_selector(".name")
for tag in select_tags:
print(tag.text)
finally:
driver.quit()
箭头
答案 0 :(得分:2)
对于这样的任务(不需要与页面进行交互),Selenium可能是多余的。 requests_html
仅几行:
from requests_html import HTMLSession
url = 'https://robertsspaceindustries.com/pledge/ship-upgrades?to-ship=173'
session = HTMLSession()
r = session.get(url)
r.html.render()
print(r.html.find('.info > .name', first=True).text)
会产生预期的Arrow
。
对于这个特定的网站,您还可以在内容的其他地方进行检查以获取所需的信息,而无需JavaScript支持,例如:
import json
import requests
url = 'https://robertsspaceindustries.com/pledge/ship-upgrades?to-ship=173'
r = requests.get(url)
text = r.text
json_start_text = 'fromShips: '
json_start = text.index(json_start_text) + len(json_start_text)
json_end = text.index(']', json_start)
json_text = text[json_start:json_end + 1]
data = json.loads(json_text)
for ship in data:
name = ship['name']
msrp = ship['msrp']
print(f'{name} {msrp}')
结果
Aurora ES $20.00
P52 Merlin $20.00
Aurora MR $25.00
P72 Archimedes $30.00
Mustang Alpha $30.00
Aurora LX $30.00
...
Arrow $75.00
...