python - 有没有办法不重复股票代码?
问题描述
import json
from io import StringIO
from bs4 import BeautifulSoup
from requests_html import HTMLSession
import time
from selenium import webdriver
import requests
import pandas as pd
PATH = "C:\Program Files (x86)\chromedriver.exe"
driver = webdriver.Chrome(PATH)
url = "https://thestockmarketwatch.com/markets/after-hours/trading.aspx"
driver.minimize_window()
driver.get(url)
time.sleep(5)
content = driver.page_source.encode('utf-8').strip()
soup = BeautifulSoup(content,"html.parser")
Afterhours = soup.find_all('a', {'class': 'symbol'})
for a in Afterhours:
print(a.text)
print("")
driver.quit()
嘿,伙计们,我正在编写这个 After-Hours Gapper刮板,我遇到了一些麻烦。股票代码正在重复它自己。我怎样才能只获得网站上显示的 , 和重复的?
解决方案
这是因为如果您查看“检查元素”选项卡并搜索类名称symbol
,您会得到 30 多个结果,这意味着具有该名称的类比您想要的要多。
让我告诉你,看看这两张图片:
第一个图像具有您想要的数据,但第二个图像在同一类中也具有相同的数据。所以你必须找到一种方法来区分这两者。可能有很多方法可以做到这一点,但我正在与您分享一种我认为有帮助的方法。
import json
from io import StringIO
from bs4 import BeautifulSoup
from requests_html import HTMLSession
import time
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager # new import
import requests
import pandas as pd
# better way to initialize the browser and driver than specifying path everytime
option = webdriver.ChromeOptions()
# option.add_argument('--headless') # uncomment to run browser in background when not debugging
option.add_argument("--log-level=3")
option.add_experimental_option('excludeSwitches', ['enable-logging'])
CDM = ChromeDriverManager(log_level='0')
driver = webdriver.Chrome(CDM.install(), options=option)
# PATH = "C:\Program Files (x86)\chromedriver.exe"
# driver = webdriver.Chrome(PATH)
url = "https://thestockmarketwatch.com/markets/after-hours/trading.aspx"
driver.minimize_window()
driver.get(url)
time.sleep(5)
content = driver.page_source.encode('utf-8').strip()
soup = BeautifulSoup(content,"html.parser")
Afterhours = soup.find_all('a', {'class': 'symbol'})
removed_duplicates =[]
for a in Afterhours:
if a.find_previous().get('style') == None: # the difference between those two duplicates
removed_duplicates.append(a)
for i in removed_duplicates:
print(i.text)
print() # just an empty print() would print a new line
driver.quit()
您现在可能已经注意到第一个标签没有任何内联样式,但第二个标签有一些。使用的最好的事情BeautifulSoup
是它有助于平滑遍历,因此您可以上下移动元素以找到您需要的任何内容。
我还在您的代码中添加了一些改进和建议,如果您已经知道它们,请忽略它们。这是个好问题!
推荐阅读
- php - 在没有 WordPress 插件的情况下重新生成缩略图
- mongodb - 节点未处于主要或恢复状态 - 迁移到新环境后的 mongodb
- curl - 如何从 RestAssured 响应返回位置标头
- react-native - @react-native-community/datetimepicker 的 CustomStyle 和 textColor 道具不起作用
- mql4 - 未平仓订单如何在相同的交易条件下继续
- c# - 为什么在 Action 和 Result 过滤器中无法访问 context.Result.StatusCode?
- woocommerce - 如何从数据库中获取保存的值并显示为 woocommerce_form_field 中的选定值?
- java - 如何从 jar 和 docker opt 目录中读取 txt 文件
- typescript - Visual Studio Code 的 Intelisense 没有更新正确?我必须检查哪个复选框?
- python - 如何使用 matplotlib 更改图例的大小?并在我的地图上识别州