我想从 html 中压缩一些列表,我使用如下代码:
html_link = 'https://www.pds.com.ph/index.html%3Fpage_id=3261.html'
html = requests.get(html_link).text
soup = BeautifulSoup(html, 'html.parser')
search = re.compile(r"March.+2021")
for td in soup.find_all('td', text=search):
link = td.parent.select_one("td > a")
if link:
titles = link.text
links = f"Link : 'https://www.pds.com.ph/{link['href']}"
dates = td.text
for link, title, date in zip(links, titles, dates):
dataframe = pd.DataFrame({'col1':title,'col2':link,'col3':date},index=[0])
print(dataframe)
但是输出不是我所期望的:
col1 col2 col3
1 P L M
col1 col2 col3
1 D i a
...
我的期望是:
Titles Links Dates
... ... ...
请问语法是否正确或者我可以做什么来实现这一点?
最佳答案
您可以将 zip
的结果直接传递到 pd.DataFrame
,并在列表中指定列名称:
df = pd.DataFrame(zip(titles, links, dates), columns=['Titles', 'Links', 'Dates'])
关于Python Zip 列表到 Dataframe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67411124/