如何使用 Python (BeautifulSoup) 从网上抓取表格?

时间:2021-07-27 10:26:02

标签: python web-scraping beautifulsoup html-table scrape

我正在尝试从网站中提取表格。我一直在使用 BeautifulSoup,但最后我在我刮掉的桌子上得到了空行。

#import package
from urllib.request import Request, urlopen
from bs4 import BeautifulSoup

#to get the html of the page
req = Request('https://covid19.go.id/peta-risiko', headers={'User-Agent': 'Mozilla/5.0'})
html = urlopen(req).read()
soup = BeautifulSoup(html, 'lxml')
type(soup)

# Get the title
title = soup.title
print(title)

# Print out the text
text = soup.get_text()
print(soup.text)

#to extract all the hyperlinks within the webpage
soup.find_all('a')

#use a for loop and the get('"href") method to extract and print out only hyperlinks
all_links = soup.find_all("a")

#To print out table rows only, pass the 'tr' argument in soup.find_all()
for link in all_links:
    print(link.get("href"))

# Print the first 10 rows for checking
rows = soup.find_all('tr')
print(rows[:10])

打印前 10 行时得到 []。我不知道这可能发生。是不是因为表格包含多个页面(第 1、2、3、下一页等)?。

在此网络上抓取此表格的任何解决方案? Web page。我想得到一个包含列的表:PROVINSI、KOTA/KABUPATEN、STATUS

0 个答案:

没有答案
相关问题