[英]Why does my Beautifulsoup element stay the same if element on the website changes?
import requests, bs4
import time
def get_tesla_price():
website = "https://finance.yahoo.com/quote/TSLA/"
res = requests.get(website)
soup = bs4.BeautifulSoup(res.text, 'html.parser')
elem = soup.select("span[class='Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)']")
price = elem[0].getText()
print(price)
for _ in range(10):
get_tesla_price()
time.sleep(2)
Above is some code which should scrape the current value of the tesla stock.上面是一些代码,可以抓取特斯拉股票的当前价值。 If you run it you will see that price
stays the same for all 10 function calls.如果您运行它,您将看到所有 10 个函数调用的price
保持不变。 But if you check the website in website
you see that the price of the stock changes almost every second.但是,如果您查看网站中的website
您会发现股票价格几乎每秒都在变化。
Why, every time when i call my function, price
is the same value?为什么每次我调用我的函数时, price
都是相同的值?
This is because of your user agent, yahoo detects you are a robot, add user agent in headers:这是因为您的用户代理,雅虎检测到您是机器人,在标题中添加用户代理:
def get_tesla_price():
website = "https://finance.yahoo.com/quote/TSLA/"
res = requests.get(website, headers={'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36'})
soup = bs4.BeautifulSoup(res.text, 'html.parser')
elem = soup.select("span[class='Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)']")
price = elem[0].getText()
res.close()
print(price)
Or you can do it with just one module requests-html:或者你可以只用一个模块 requests-html 来完成:
from requests_html import HTMLSession
import time
session = HTMLSession()
def get_tesla_price():
website = "https://finance.yahoo.com/quote/TSLA/"
r = session.get(website)
price = r.html.find("span[class='Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)']", first=True)
print(price.text)
for _ in range(20):
get_tesla_price()
time.sleep(1)
output:输出:
682.66
682.66
682.53
682.53
682.53
682.65
682.62
682.69
682.65
682.71
682.71
682.83
682.83
682.83
682.83
682.79
682.79
682.79
682.79
682.80
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.