如何在每个元素中迭代?

发布于 2025-02-08 10:21:21 字数 474 浏览 1 评论 0原文

import requests
from bs4 import BeautifulSoup

url = "https://bigpara.hurriyet.com.tr/borsa/hisse-fiyatlari/"

r = requests.get(url)
soup = BeautifulSoup(r.content,"lxml")
details = soup.find_all("div",attrs={"class":"tBody"})
#print(type(details))

for detail in details:
    
    print("{} {}".format(
        detail.a.string,
        detail.find("li",attrs={"class":"cell004"}).text.strip()
        ))

我们需要将股票与美丽的小组一起拿走。代码仅迭代第一个元素。如何迭代每个人?

import requests
from bs4 import BeautifulSoup

url = "https://bigpara.hurriyet.com.tr/borsa/hisse-fiyatlari/"

r = requests.get(url)
soup = BeautifulSoup(r.content,"lxml")
details = soup.find_all("div",attrs={"class":"tBody"})
#print(type(details))

for detail in details:
    
    print("{} {}".format(
        detail.a.string,
        detail.find("li",attrs={"class":"cell004"}).text.strip()
        ))

We need to take the stocks with BeautifulSoup. Code only iterates the first element. How to iterate each one?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浅紫色的梦幻 2025-02-15 10:21:21

首先找到所有ul元素,然后迭代其根据class明智的以dict> dict1使用键标题找到标题和值

dict1={}
for ul in details.find_all("ul"):
    title=ul.find("li",class_="cell003 tal arrow").get_text()
    values=[i.get_text(strip=True) for i in ul.find_all("li",class_=["cell004","cell003"])][1:]
    dict1[title]=values

现在您可以使用pandas模块使用pd.dataframe方法将数据转换为数据框,并根据所需的

import pandas as pd

df=pd.DataFrame(dict1)
df=df.transpose()

columns=[i.get_text(strip=True) for i in soup.find("div",class_="tHead").find_all("li")][1:]
df.columns=columns

输出获取数据:

           Son    Dün   ( % )   Yüksek  Düşük   Ağ. Ort  Hacim(LOT) Hacim(TL)
ACSEL   51,00   50,55   0,89    51,45   50,25   50,84   183.227 9.315.538
ADEL    22,98   22,98   0,00    23,20   22,72   22,93   67.600  1.550.269
.....

First find all ul elements and iterate over it to find title and values according to class wise and append items to dict1 with key title

dict1={}
for ul in details.find_all("ul"):
    title=ul.find("li",class_="cell003 tal arrow").get_text()
    values=[i.get_text(strip=True) for i in ul.find_all("li",class_=["cell004","cell003"])][1:]
    dict1[title]=values

Now you can use pandas module to transform data to DataFrame using pd.DataFrame method and get data according to required

import pandas as pd

df=pd.DataFrame(dict1)
df=df.transpose()

columns=[i.get_text(strip=True) for i in soup.find("div",class_="tHead").find_all("li")][1:]
df.columns=columns

Output:

           Son    Dün   ( % )   Yüksek  Düşük   Ağ. Ort  Hacim(LOT) Hacim(TL)
ACSEL   51,00   50,55   0,89    51,45   50,25   50,84   183.227 9.315.538
ADEL    22,98   22,98   0,00    23,20   22,72   22,93   67.600  1.550.269
.....
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文