尝试从网页上打印所有TR元素和所有TD元素

时间:2018-08-31 15:42:17

标签: python python-3.x

我正在使用下面的脚本,并试图使其将网页中的所有TR元素和所有TD元素写入CSV文件。由于某些未知的原因,我在CSV文件中根本没有任何数据。

from bs4 import BeautifulSoup
import requests
import pandas as pd
import csv

url = "https://my_url"
page = requests.get(url)
pagetext = page.text

soup = BeautifulSoup(pagetext, 'html.parser')

file = open("C:/my_path/test.csv", 'w')

for row in soup.find_all('tr'):
    for col in row.find_all('td'):
        print(col.text)

我正在使用Python 3.6。

1 个答案:

答案 0 :(得分:4)

您的网址不是网站,因此无法找到任何内容。您只需要修复该网址,然后重试即可。

我已修复代码,以便您可以完成它。只会将列表中的第一行数据添加到csv文件中。

from bs4 import BeautifulSoup
import requests
import pandas as pd
import csv

url = "https://www.w3schools.com/html/html_tables.asp"
page = requests.get(url)
pagetext = page.text

soup = BeautifulSoup(pagetext, 'html.parser')

file = open("C:/Test/test2.csv", 'w')

for row in soup.find_all('tr'):
    for col in row.find_all('td'):
        info= col.text
        print(info)


file.write(info)
file.close()
相关问题