【发布时间】:2021-10-24 16:04:18
【问题描述】:
我一直在使用 python 中的网络抓取工具来抓取 Google Finance,但我无法使用 find() 方法找到我正在寻找的特定标签。最后,我很生气,我决定将返回的数据写入文件并自己查找。所以我把它写到同一目录下的 testing.html 中,然后用 Google Chromium 打开它,这样我就可以使用检查工具了。几分钟之内,我就找到了我正在寻找的元素。我究竟做错了什么?我的代码附在下面:
import dryscrape
session = dryscrape.Session()
def get(url):
global session
try:
session.visit(url)
data = session.body()
except:
print('Connection Failed')
return str(data)
def save(price, stockname):
pass
def extract(data):
return data.find('<div class="YMLKec fxKbKc">')
class following():
apple = "https://www.google.com/finance/quote/AAPL:NASDAQ"
tesla = "https://www.google.com/finance/quote/TSLA:NASDAQ"
google = "https://www.google.com/finance/quote/GOOGL:NASDAQ"
amazon = "https://www.google.com/finance/quote/AMZN:NASDAQ"
microsoft = "https://www.google.com/finance/quote/MSFT:NASDAQ"
netflix = "https://www.google.com/finance/quote/NFLX:NASDAQ"
def __init__():
global apple
global tesla
global google
global amazon
global microsoft
global netflix
save(extract(get(following.apple)), following.apple)
save(extract(get(following.tesla)), following.tesla)
save(extract(get(following.google)), following.google)
save(extract(get(following.amazon)), following.amazon)
save(extract(get(following.microsoft)), following.microsoft)
save(extract(get(following.netflix)), following.netflix)
f = open("testing.html")
print(extract(f.read()))
f.close()
【问题讨论】:
-
也许类描述是单独的并且每次重新加载后都会改变?为什么不使用 BeautifulSoup 来解析 HTML?让工作更容易恕我直言。
-
我只需要一个值,所以我认为漂亮的汤有点矫枉过正。我查了一下,过去三天的课程完全一样。 @js-on
-
查看您要查找的 html 源代码片段可能很有用,可以将其添加为您的问题的一部分吗?
-
您能否验证您要查找的字符串是否存在于 testing.html 中?如果您使用检查工具找到它,则该内容可能是由一些 javascript 加载的,并且不能那么容易地获取。这只是一个理论,不知道dryscraper是如何工作的。
-
删除站点的缓存和cookies,清除检查工具的网络选项卡中的所有条目,然后按Ctrl + F5(重新加载)页面。如果已获取所有数据,请搜索该字符串,您将有望获得正确的数据来源。
标签: python web-scraping dryscrape