วิธีพิมพ์รายการนี้ลงใน DataFrame -Python / BeautifulSoup

Oct 22 2020

ผลลัพธ์ของรหัสนี้จะพิมพ์แต่ละแถวบนเว็บไซต์ที่ให้ไว้ด้านล่าง

อย่างไรก็ตามยังรวมถึงแท็ก โดยพื้นฐานแล้วฉันต้องการพิมพ์แถวทั้งหมดลงใน dataFrame ซึ่งฉันสามารถใส่ใน Excel ได้

.text ใช้งานไม่ได้เพราะฉันใช้ find_all เนื่องจากมีแท็กที่ซ้ำกันในชื่อ

ขั้นตอนจะเป็นอย่างไรในการลบแท็กที่ไม่ต้องการจากนั้นให้รายชื่อลงใน DF เพื่อจำลองเว็บไซต์

ขอบคุณ.

import requests
from bs4 import BeautifulSoup
import pandas as pd
productlinks=[]
r=requests.get(url)
soup= BeautifulSoup(r.content,'html.parser')
content=soup.find_all('tr')
for item in content:
    title=item.find_all('td')
    print(title)

คำตอบ

1 AndrejKesely Oct 22 2020 at 04:03

วิธีที่ง่ายที่สุดคือใช้pandas.read_html:

import pandas as pd

url='https://sitc.sitcancer.org/2020/abstracts/titles/'
df = pd.read_html(url)[0]
print(df)
df.to_csv('data.csv', index=False)

พิมพ์:

       #  ...                                           Keywords
0      1  ...  Adoptive immunotherapy; Monocyte/Macrophage; T...
1      2  ...  CAR T cells; Immune monitoring; Inflammation; ...
2      3  ...  Antibody; Biomarkers; Immune monitoring; T cel...
3      4  ...  Biomarkers; RNA; Solid tumors; Tumor microenvi...
4      5  ...  Antibody; B cell; Biomarkers; Immune monitorin...
..   ...  ...                                                ...
730  752  ...  Gene expression; Neoantigens; Regulatory T cel...
731  753  ...  Gene expression; Neoantigens; Regulatory T cel...
732  754  ...  Biomarkers; Chemokine; Chemotherapy; Costimula...
733  755  ...  Chemokine; Granulocyte; Myeloid cells; MDSC; T...
734  756  ...  Gene expression; Immune contexture; Immune sup...

[735 rows x 6 columns]

และบันทึกdata.csv(ภาพหน้าจอจาก LibreOffice):