使用find在python中创建一个html表

2024-05-13 08:09:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python的新手,我正在尝试从一个网页中获取一个表。我已经通过Chrome中的“inspect”访问了html。网页如下:

https://www.basketball-reference.com/players/a/abdelal01.html

下面是我使用的代码

import bs4
from urllib2 import urlopen as uReq
from bs4 import BeautifulSoup as soup

#name a page to scrape
my_url = 'https://www.basketball-reference.com/players/a/abdelal01.html'

uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()

#perform html parsing
page_soup = soup(page_html, "html.parser")

这一页上有一张表格叫“工资”。我想刮这个表,连同网页的标题,并最终把他们在一个csv文件。不过,我首先要拿到工资表。我一直在尝试使用来自BeautifulSoupfind函数,因为它只是我感兴趣的一个表。问题是运行以下代码时没有得到任何结果:

page_soup.find("table", id = "all_salaries")

我使用的是Chrome,当我使用桌面上的“inspect”工具时,它看起来像是“all\ u palares”,但我没有得到任何结果。我没有结果有什么原因吗?正确的方法是什么?你知道吗


Tags: httpsimportcom网页htmlwwwpagechrome
1条回答
网友
1楼 · 发布于 2024-05-13 08:09:58

这可以通过csvwriter和find_all函数来实现。你知道吗

import bs4, csv
from urllib2 import urlopen as uReq
from bs4 import BeautifulSoup as soup

#name a page to scrape
my_url = 'https://www.basketball-reference.com/players/a/abdelal01.html'

uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()

#perform html parsing
page_soup = soup(page_html, "html.parser")

with open('csvOut.csv','w') as myFile:
    writer = csv.writer(myFile, lineterminator='\n')
    table = page_soup.find({"class" : "full_table"})
    for row in page_soup.find_all("tr"):
        rowTds = [td.text for td in row.find_all("td")]
        if len(rowTds):
            writer.writerow(rowTds)

相关问题 更多 >