Я использовал список распаковки и фрагменты, чтобы выбрать нужные ячейки из строки таблицы, затем извлек их текст.Нарезка списка столбцов с помощью [2:5]
делает свое дело.
import requests
from bs4 import BeautifulSoup
import re
def make_soup(url: str) -> BeautifulSoup:
res = requests.get(url)
res.raise_for_status()
return BeautifulSoup(res.text, 'html.parser')
def extract_purchases(soup: BeautifulSoup) -> list:
table = soup.find('th', text=re.compile('Date of Purchase')).find_parent('table')
purchases = []
for row in table.find_all('tr')[1:]:
price_cell, qty_cell, date_cell = row.find_all('td')[2:5]
p = {
'price': price_cell.text.strip(),
'quantity': qty_cell.text.strip(),
'date': date_cell.text.strip()
}
purchases.append(p)
return purchases
if __name__ == '__main__':
url = 'https://offer.ebay.com/ws/eBayISAPI.dll?ViewBidsLogin&item=173653442617&rt=nc&_trksid=p2047675.l2564'
soup = make_soup(url)
purchases = extract_purchases(soup)
from pprint import pprint
pprint(purchases)
вывод:
[{'date': 'Jul-02-19 18:22:28 PDT', 'price': 'US $54.08', 'quantity': '1'},
{'date': 'Jun-27-19 16:12:59 PDT', 'price': 'US $54.08', 'quantity': '1'},
{'date': 'Jun-23-19 06:46:23 PDT', 'price': 'US $54.08', 'quantity': '1'},
{'date': 'Jun-20-19 09:14:07 PDT', 'price': 'US $54.08', 'quantity': '1'},
{'date': 'May-23-19 09:48:59 PDT', 'price': 'US $63.04', 'quantity': '1'},
{'date': 'May-20-19 06:05:24 PDT', 'price': 'US $63.04', 'quantity': '1'},
{'date': 'May-17-19 13:10:38 PDT', 'price': 'US $63.04', 'quantity': '1'},
{'date': 'May-04-19 17:11:32 PDT', 'price': 'US $55.36', 'quantity': '1'},
{'date': 'Apr-24-19 15:27:42 PDT', 'price': 'US $55.36', 'quantity': '1'},
{'date': 'Apr-07-19 17:03:05 PDT', 'price': 'US $54.08', 'quantity': '1'},
{'date': 'Apr-06-19 21:20:17 PDT', 'price': 'US $54.08', 'quantity': '1'},
{'date': 'Apr-06-19 13:29:45 PDT', 'price': 'US $54.08', 'quantity': '1'},
{'date': 'Apr-05-19 14:42:23 PDT', 'price': 'US $54.08', 'quantity': '1'},
{'date': 'Apr-03-19 21:37:14 PDT', 'price': 'US $54.08', 'quantity': '1'},
{'date': 'Apr-02-19 18:23:45 PDT', 'price': 'US $54.08', 'quantity': '1'},
{'date': 'Mar-31-19 06:01:36 PDT', 'price': 'US $54.08', 'quantity': '1'},
{'date': 'Mar-25-19 14:37:27 PDT', 'price': 'US $56.64', 'quantity': '1'},
{'date': 'Feb-12-19 10:57:22 PST', 'price': 'US $53.94', 'quantity': '1'}]