4 回答

TA貢獻1788條經驗 獲得超4個贊
在我看來,您的第二個 for 循環for p_tag in item.find_all('p'):
不在第一個 for 循環的范圍內,該循環遍歷項目...添加到第一個循環中可能有 0 個項目的事實,您得到一個無。
只需將 for 循環及其內容放在迭代 pipeline_items 中的項目的 for 循環中。

TA貢獻1773條經驗 獲得超3個贊
問題是
pipeline_items = soup.find_all('div', attrs={'class': 'pipline-item'})
返回一個空列表。這樣做的結果是:
for item in pipeline_items:
從來沒有真正發生過。因此,item
永遠不會定義 的值。
我不確定你到底想做什么。但我看到兩個解決方案:
縮進
for p_tag in item.find_all('p'):
以便為每個項目執行它。這樣,如果沒有項目,它就不會被調用(我想這就是你原本打算做的?)在循環前加if語句判斷是否
item
存在,不存在則跳過循環。哪個最接近復制您的代碼當前正在執行的操作,但我認為這不是您希望它執行的操作。

TA貢獻1854條經驗 獲得超8個贊
第 17 行及以下需要在 for 循環內才能看到“item”。
for item in pipeline_items:
# title, image url, listing url
listing_title = item.a['title']
listing_url = item.a['href']
listing_image_url = item.a.img['src']
for p_tag in item.find_all('p'): <------------Indent this for loop to be inside the previous for loop.
if not p_tag.h2:
if p_tag.text == 'Location:':

TA貢獻1835條經驗 獲得超7個贊
任務完成感謝這里的每一個人,干杯!我遺漏了一些東西。1 確定縮進。2 我錯過了第一小節的跨度——如果 p_tag.span.text == 'Location:': 3 我錯過了一個包 openpyxl,它在底部被調用以寫入 excel。
下面 100% 的工作代碼,我承諾會變得更好并在我可以的時候提供幫助 :)
import requests
from bs4 import BeautifulSoup
import pandas as pd
url = 'https://dc.urbanturf.com/pipeline'
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
pipeline_items = soup.find_all('div', attrs={'class': 'pipeline-item'})
rows = []
columns = ['listing title', 'listing url', 'listing image url', 'location', 'Project type', 'Status', 'Size']
for item in pipeline_items:
# title, image url, listing url
listing_title = item.a['title']
listing_url = item.a['href']
listing_image_url = item.a.img['src']
for p_tag in item.find_all('p'):
if not p_tag.h2:
if p_tag.span.text == 'Location:':
p_tag.span.extract()
property_location = p_tag.text.strip()
elif p_tag.span.text == 'Project type:':
p_tag.span.extract()
property_type = p_tag.text.strip()
elif p_tag.span.text == 'Status:':
p_tag.span.extract()
property_status = p_tag.text.strip()
elif p_tag.span.text == 'Size:':
p_tag.span.extract()
property_size = p_tag.text.strip()
row = [listing_title, listing_url, listing_image_url, property_location, property_type, property_status, property_size]
rows.append(row)
df = pd.DataFrame(rows, columns=columns)
df.to_excel('DC Pipeline Properties.xlsx', index=False)
print('File Saved')
添加回答
舉報