python - Wiki Scraping 缺失数据
问题描述
我正在尝试从https://en.wikipedia.org/wiki/Megacity中提取表格,作为我最初涉足抓取世界的尝试(以完全透明的方式,我从阅读的博客中获取了这段代码)。我让程序正常工作,但我没有得到城市,而是 \n (也在每个字段上。问题:为什么我在每个字段的末尾都有 \n ,为什么我的第一个字段(城市)是空白的?下面列出是代码和输出的一部分。
import requests
scrapeLink = 'https://en.wikipedia.org/wiki/Megacity'
page = requests.get(scrapeLink)
from bs4 import BeautifulSoup
soup = BeautifulSoup(page.content, 'html.parser')
megaTable = soup.find_all('table')[1]
rowValList = []
for i in range(len(megaTable.find_all('td'))):
rowVal = megaTable.find_all('td')[i].get_text()
rowValList.append(rowVal)
cityList = []
for i in range(0, len(rowValList), 6):
cityList.append(rowValList[i])
countryList = []
for i in range(1, len(rowValList), 6):
countryList.append(rowValList[i])
contList = []
for i in range(2, len(rowValList), 6):
contList.append(rowValList[i])
popList = []
for i in range(3, len(rowValList), 6):
popList.append(rowValList[i])
import pandas as pd
megaDf = pd.DataFrame()
megaDf['City'] = cityList
megaDf['Country'] = countryList
megaDf['Continent'] = contList
megaDf['Population'] = popList
megaDf
解决方案
原因是城市不在td
标签内,而是在th
标签内。
<th scope="row"><a href="/wiki/Bangalore" title="Bangalore">Bangalore</a></th>
您所指的第一个 td 实际上是图像列。th
您可以通过获取标签来选择城市名称。
此外,您可以通过首先获取表格的行然后为每一行选择必要的标签来简化您的爬虫,即th
和td
。
import requests
from bs4 import BeautifulSoup
scrapeLink = "https://en.wikipedia.org/wiki/Megacity"
page = requests.get(scrapeLink)
soup = BeautifulSoup(page.content, "html.parser")
megaTable = soup.find_all("table")[1]
cities = []
# [:2] slices the array since the first 2 `tr` contains the headers
for row in megaTable.find_all("tr")[2:]:
city = row.th.get_text().strip()
tds = row.find_all("td")
country = tds[1].get_text().strip()
continent = tds[2].get_text().strip()
population = tds[3].get_text().strip()
cities.append({
"city": city,
"country": country,
"continent": continent,
"popluation": population,
})
print(cities)
[
{
"city": "Bangalore",
"country": "India",
"continent": "Asia",
"population": "12,200,00"
},
# and so on
]
然后,您可以将列表转换为数据框:
df = pd.DataFrame(cities)
推荐阅读
- python-3.x - 如何从其他文件夹导入 python 模块
- javascript - javascript中的百分比,然后从百分比反转为targetValue
- c# - 在 Azure Bot Framework 的 WaterfallDialog 中,我们如何进行特定步骤?
- python - AttributeError:模块“pygmo”没有属性“spea2”
- python - 我将两个整数设置为彼此相等,但我仍然得到:'int' object is not subscriptable?
- c# - 如何读取 Xml,然后在 C# 中以不同格式编写 Xml
- ruby - CGI.escape 空间问题。需要为 Magento 生成 oauth 签名
- javascript - 在rails中成功提交表单数据后如何隐藏我的引导模式表单
- google-apps-script - 自动切换工作表/选项卡的脚本
- javascript - JavaScript 未在计算中显示准确值