【问题标题】:How to scrape a table but 'not a table' from a page, using python?如何使用 python 从页面中抓取表格但“不是表格”?
【发布时间】:2023-01-21 09:10:04
【问题描述】:

谦虚的问候,欢迎任何愿意在这里度过时光的人。我将自我介绍为数据科学和 Python 的非常新的学生。这个线程旨在从能够在 python 领域内更深入理解的更幸运的头脑中获得洞察力。

如我们所见,在页面检查中可以很容易地找到每一行本身的值。但似乎他们都在使用相同的类名。至于现在,恐怕我什至找不到合适的关键字来搜索谷歌中的任何工作方法。

这些是我试过的代码。他们不工作和令人尴尬,但我无论如何都必须展示它。我尝试通过添加 .content、.text、find、find_all 来摆弄,但我知道我的失败在于更深的基本核心。

from bs4 import BeautifulSoup
import requests
from csv import writer
import pandas as pd

url= 'https://m4.mobilelegends.com/stats'
page = requests.get(url)

soup = BeautifulSoup(page.text, 'html.parser')
lists = soup.find('div', class_="m4-team-stats-scroll")

with open('m4stats_team.csv', 'w', encoding='utf8', newline='') as f:
    thewriter = writer(f)
    header = ['Team', 'Win Rate', 'Average KDA', 'Average Kills', 'average Deaths', 'Average Assists', 'Average Game Time', 'Average Lord Kills', 'Average Tortoise Kills', 'Average Towers Destroy', 'First Blood Rate', 'Hero Pool']
    thewriter.writerow(header)

    for list in lists:
        team = list.find_all('p', class_="h3 pl-5 whitespace-nowrap hidden xl:block")
        awr = list.find_all('p', class_="h4")
        akda = list.find('p', class_="h4").text
        akill = list.find('p', class_="h4").text
        adeath = list.find('p', class_="h4").text
        aassist = list.find('p', class_="h4").text
        atime = list.find('p', class_="h4").text
        aalord = list.find('p', class_="h4").text
        atortoise = list.find('p', class_="h4").text
        atower = list.find('p', class_="h4").text
        firstblood = list.find('p', class_="h4").text
        hrpool = list.find('p', class_="h4").text


        info = [team, awr, akda, akill, adeath, aassist, atime, aalord, atortoise, atower, firstblood, hrpool]
        thewriter.writerow(info)

pd.read_csv('m4stats_team.csv').head()

我在期待什么: 任何一种洞察力。无论是线索、关键字、代码 sn-p,我都非常感谢并非常感谢您提供的任何指导。我不是要求以某种方式获得完整的报废 CSV,因为我可以手动完成。在这一点上,我希望能够自己进行基本的网络抓取。

【问题讨论】:

  • 现在只需将此链接中的 1674043547673 更改为时间戳 m4.mobilelegends.com/data/version/240/teams.csv?v=1674043547673
  • 抱歉。你是如何设法找到这个数据源的?
  • chrome 开发工具,网络选项卡
  • 哦,我知道你是怎么到那里的。在我的浏览器中,我还可以使用检查元素并从网络选项卡中找到任何相关的 csv。对于这一见解,我非常感谢您,先生。

标签: python web-scraping beautifulsoup python-requests-html


【解决方案1】:

您可以遍历表中的行及其项目。

from bs4 import BeautifulSoup
import requests

page = requests.get('https://m4.mobilelegends.com/stats')
page.raise_for_status()

page = BeautifulSoup(page.content)

table = page.find("div", class_="m4-team-stats-scroll")

with open("table.csv", "w") as file:
    for row in table.find_all("div", class_="m4-team-stats"):
        items = row.find_all("div", class_="col-span-1")
        # write into file in csv format, use map to extract text from items
        file.write(",".join(map(lambda item: item.text, items)) + "
")

显示输出:

import pandas as pd

df = pd.read_csv("table.csv")

print(df)

# Outputs:
"""
      Team ↓Win Rate  ...  ↓First Blood Rate  ↓Hero pool
0     echo     72.0%  ...              48.0%          37
1      rrq     60.9%  ...              60.9%          37
2       tv     60.0%  ...              60.0%          29
3     fcon     55.0%  ...              85.0%          32
4      inc     53.3%  ...              26.7%          31
5     onic     52.9%  ...              47.1%          39
6     blck     52.2%  ...              47.8%          31
7   rrq-br     46.2%  ...              30.8%          32
8      thq     45.5%  ...              63.6%          27
9      s11     42.9%  ...              28.6%          26
10     tdk     37.5%  ...              62.5%          24
11      ot     28.6%  ...              28.6%          21
12     mvg     20.0%  ...              20.0%          15
13  rsg-sg     20.0%  ...              60.0%          17
14    burn      0.0%  ...              20.0%          21
15     mdh      0.0%  ...              40.0%          18

[16 rows x 12 columns]
"""

【讨论】:

  • 这段代码对我来说效果很好,同时也启发了我在这种情况下应该做什么——我在选择哪个参数和类来获取值时错了——我应该使用逗号分隔符和 lambda 并添加手动换行符以确保记录器文本变成正确的 CSV 格式——此外,我尝试不使用 raise status 并添加 encoding='utf-8' 以使其在我的机器上工作,非常感谢你的课程。愿你的旅程充满成功。
  • 抱歉,我对包括堆栈溢出在内的任何编码环境都非常陌生。我已通过单击复选标记图标接受了您的回答。
【解决方案2】:

Python 中有几个库可用于从网页中抓取表格,例如 BeautifulSoup 和 pandas。以下是如何使用 BeautifulSoup 从网页中抓取表格的示例:

import requests
from bs4 import BeautifulSoup 
url = "https://example.com" 
page = requests.get(url) 
soup = BeautifulSoup(page.content, 'html.parser') 
table = soup.find_all('table')[0]

在此示例中,requests.get(url) 检索指定 URL 网页的 HTML 内容,BeautifulSoup(page.content, 'html.parser') 解析 HTML 内容。然后使用 find_all() 方法查找页面上的所有表格元素,并将第一个赋值给变量 table。

要抓取非表格元素,您可以使用相同的方法,但您可以搜索任何其他元素,例如 div、span、p 等,而不是搜索表格元素。

import requests 
from bs4 import BeautifulSoup 
url = "https://example.com" 
page = requests.get(url) 
soup = BeautifulSoup(page.content, 'html.parser') 
not_a_table = soup.find_all('div', {'class': 'not-a-table'})[0]

在这个例子中,soup.find_all('div', {'class': 'not-a-table'}) 在页面上找到所有类为“not-a-table”的 div 元素,第一个被赋值给变量 not_a_table。

请记住,网站可能有隐私政策、服务条款和版权法,禁止未经许可抓取其内容。如果您无法从此代码中找到帮助,可以按照data science 和数据挖掘过程中的指南进行操作。

【讨论】:

    猜你喜欢
    • 2017-07-07
    • 2016-10-19
    • 2021-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-08
    相关资源
    最近更新 更多