0
import requests
import csv
import requests
from bs4 import BeautifulSoup

r = requests.get('https://pqt.cbp.gov/report/YYZ_1/12-01-2017')
soup = BeautifulSoup(r)
table = soup.find('table', attrs={ "class" : "table-horizontal-line"})
headers = [header.text for header in table.find_all('th')]
rows = []
for row in table.find_all('tr'):
    rows.append([val.text.encode('utf8') for val in row.find_all('td')])

with open('output_file.csv', 'wb') as f:
    writer = csv.writer(f)
    writer.writerow(headers)
    writer.writerows(row for row in rows if row)

I am trying to parse all table data in this particular webpage: https://pqt.cbp.gov/report/YYZ_1/12-01-2017

I am getting an error in the line soup = BeautifulSoup(r). I get an error TypeError: object of type 'Response' has no len(). I am also not sure if my logic is correct. Plz help me pasing the table data.

3 Answers 3

1

I would do it this way

import pandas as pd
result = pd.read_html("https://pqt.cbp.gov/report/YYZ_1/12-01-2017")
df = result[0]
# df = df.drop(labels='Unnamed: 8', axis=1)
df.to_csv(r'C:\Users\User\Desktop\Data.csv', sep=',', encoding='utf-8',index = False )
Sign up to request clarification or add additional context in comments.

3 Comments

After u made the edit, the output file does not appear without an error. You were dropping the last row, right?
The last column
But simply exclude the 4th line above
0

try:

r = requests.get('https://pqt.cbp.gov/report/YYZ_1/12-01-2017')
soup = BeautifulSoup(r.content)

1 Comment

Now I get an error on headers = [header.text for header in table.find_all('th')] AttributeError: 'NoneType' object has no attribute 'find_all''
0

variable r is type Response not str, use r.text or r.content and there are no table with class table-horizontal-line, do you mean results ?

soup = BeautifulSoup(r.text)
table = soup.find('table', attrs={"class" : "results"})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.