如何解析并记录在标签下的表格中td a href?
import requests
from bs4 import BeautifulSoup
import csv
count = 0
headers = {
"Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:83.0) Gecko/20100101 Firefox/83.0"
}
with open("result.csv", "w", encoding='utf-8') as file:
writer = csv.writer(file)
writer.writerow(["#", "АДРЕС", "ТЕЛЕФОН", "ВРЕМЯ РАБОТЫ", "КОЛИЧЕСТВО", "ЦЕНА"])
for num in range(1, 32):
req = requests.get(f"https://apteka.net.ua/search/availability/6810/page-{num}?region=&city=", headers=headers)
soup = BeautifulSoup(req.content, 'html.parser')
for i in soup.find("table").find_all("td"):
try:
adress = i.find(class_="col_address").find_all("a")
for k in adress:
adr = k.text
phones = i.find(class_="col_phone").find_all("a")
for j in adress:
adr = j.text
work_time = i.find(class_="col_work").text
quantity = i.find(class_="col_quantity").text
prices = i.find(class_="quantity").text
count += 1
except Exception as e:
print(e)
try:
writer.writerow([count,adr,phones,work_time,quantity,prices])
except Exception as e:
print(e)
给出错误消息:
'NoneType' object has no attribute 'find_all'
name 'adr' is not defined
我重写了代码,主要问题是您不是逐行解析(也就是说,您必须通过标签
tr),而是逐行解析。尝试: