从html文本中提取表

时间:2019-02-24 12:55:05

标签: beautifulsoup lxml

我正在尝试从页面提取文本并将其另存为数据框。该页面未格式化为标签,因此熊猫无法直接读取它。我尝试使用bs4,但无法提取确切的URL。

from bs4 import BeautifulSoup

html = requests.get('https://s3.amazonaws.com/todel162/veryimp/claps-0001.html')
soup = BeautifulSoup(html.text, "lxml") 


links = soup.find_all('li')

import pandas as pd
df = pd.DataFrame(links)

我期望4列的数据框,像这样...

vote title date url
1 How a TV Sitcom Triggered the Downfall of Western Civilization 2016-03-23 12:23 https://medium.com/p/how-a-tv-sitcom-triggered-the-downfall-of-western-civilization-336e8ccf7dd0

2 个答案:

答案 0 :(得分:4)

soup.find_all('li')仅返回页面中的所有li标签。您需要做的是从每个li标签中获取相关信息,例如投票,标题,日期和网址,然后将其保存到列表中。然后,您可以将其转换为数据框。您可以通过使用'href'标签的'a'属性来使用BeautifulSoup获取该网址。

from bs4 import BeautifulSoup
import requests
import pandas as pd
html = requests.get('https://s3.amazonaws.com/todel162/veryimp/claps-0001.html')
soup = BeautifulSoup(html.text, "lxml")
links = soup.find_all('li')
final_list=[]
for li in links:
    votes=li.contents[0].split(' ')[0]
    title=li.find('a').text
    date=li.find('time').text
    url=li.find('a')['href']
    final_list.append([votes,title,date,url])
df = pd.DataFrame(final_list,columns=['Votes', 'title', 'Date','Url'])
print(df)
#just df if in Jupyter notebook

Jupyter笔记本的示例输出

enter image description here

答案 1 :(得分:1)

您需要解析html。 find_all('li')只是在hmtl中找到您需要的所有li。

这是所有代码:

html = requests.get('https://s3.amazonaws.com/todel162/veryimp/claps-0001.html')
soup = BeautifulSoup(html.text, "html.parser")
import pandas as pd

links = soup.find_all('li')

all = []
for elements in links:
    find_a = elements.find('a')
    vote = find_a.previous_sibling
    vote =int(re.search(r'\d+', vote).group()) #remove the + and - Just get int
    title = find_a.text
    date = elements.find('time',attrs={'class' : 'dt-published'}).text
    url = find_a['href']
    all.append([vote,title,date,url])

dataf = pd.DataFrame(all,columns=['vote', 'title', 'date','url'])

print(dataf)