我是Python的新手,并尝试制作Google搜索剪贴簿以获取股票价格,但我在下面运行我的代码我没有得到任何结果而是我得到页面HTML格式。
import urllib.request
from bs4 import BeautifulSoup
import requests
url = 'https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=uwti'
response = requests.get(url)
html = response.content
soup = BeautifulSoup(html, "html.parser")
print(soup.prettify())
我错过了一些非常简单的事情,请给我一些指示。我正在尝试提取当前的股票价值。如何在附加图像中提取此值?
答案 0 :(得分:3)
右键单击并在浏览器中选择view-source时,它位于源代码中。您只需稍微更改 url 并传递用户代理以匹配您在那里使用请求所看到的内容:
In [2]: from bs4 import BeautifulSoup
...: import requests
...:
...: url = 'https://www.google.com/search?q=uwti&rct=j'
...: response = requests.get(url, headers={
...: "user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (K
...: HTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36"})
...: html = response.content
...:
...: soup = BeautifulSoup(html, "html.parser")
...: print(soup.select_one("span._Rnb.fmob_pr.fac-l").text)
...:
27.51
soup.find("span", class_="_Rnb fmob_pr fac-l").text
也可以使用 css类查找或 find_all
使用https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=uwti时,您可以在Chrome中看到,重定向到https://www.google.com/search?q=uwti&rct=j:
答案 1 :(得分:1)
很容易做到:
add_action( 'woocommerce_order_status_processing', 'add_order_meta_from_custom_user_meta', 10, 2 );
添加到您的请求中,以便 Google 将您的请求视为真正的用户访问。 List 个用户代理。user-agent
选择器CSS
选择器与 .select_one()
css
方法结合使用以获取数据。bs4
或者,您可以使用来自 SerpApi 的 Google Direct Answer Box API 来做同样的事情。这是一个付费 API,可免费试用 5,000 次搜索。
本示例中最大的不同在于,您不必弄清楚为什么某些东西不起作用,也不必弄清楚如何抓取这些数据。获取数据的过程就清晰多了。
要集成的代码:
from bs4 import BeautifulSoup
import requests, lxml
headers = {
'User-agent':
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582"
}
html = requests.get('https://www.google.com/search?q=spgsclp', headers=headers)
soup = BeautifulSoup(html.text, 'lxml')
current_stock_price = soup.select_one('.wT3VGc').text
print(current_stock_price)
>>> 108,52
<块引用>
免责声明,我为 SerpApi 工作。
答案 2 :(得分:0)
查看Beautiful Soup's
documentation,了解如何选择刚刚解析过的HTML文档的元素,您可以尝试以下内容:
soup.findAll("span", ['_Rnb', 'fmob_pr, 'fac-l'])
上面的方法将找到实现列表中类的span元素。
仅供参考:股票价格不会被我看到的初始请求提取,使用浏览器的Inspect Element
功能捕获发送的请求,从我可以看到有一个请求到网址https://www.google.gr/async/finance_price_updates
。也许这用于获取股票的价格,看看你是否可以直接发送请求而不是获取整个HTML。
答案 3 :(得分:0)
import urllib
from bs4 import BeautifulSoup
url = 'siteurl'
response = urllib.urlopen(url)
soup = BeautifulSoup(response, "html.parser")
print(soup.findAll("div", { "class" : 'classname' }))
您只需更改&#39; siteurl&#39;即可使用此代码。和&#39; classname&#39;(你必须废弃)