我要考虑的情况是当网站结构歪斜,有很多相同的类和标签。在这些类中,需要的信息在不同的索引下,其中[3],其中[6]。根本没有。假设有:'Div' class = 'data-123'
地址' Div 'class = 'data-123'
信息' Div 'class = 'data-123' Phone - 1234567890
等这是我需要得到的电话。在不同的牌中,它的顺序是随机的,或者它根本不存在。也就是说,它不会通过xpath找到它,因为它每次都不同,选择器可以与其他一些参数相同。也许通过"电话"这个词;在这堂课上?如何摆脱这种局面?
要获取公司名称和电话号码,您可以这样做:
import requests
from bs4 import BeautifulSoup
url = "https://www.ua-region.com.ua/ru/kved/49.41"
soup = BeautifulSoup(requests.get(url).content, "html.parser")
for company in soup.select(".cart-company-lg"):
title = company.select_one(".cart-company-lg__title").text
telephones = [t.text for t in company.select('[href^="tel"]')]
print(title)
print(*telephones)
print("-" * 80)
打印:
СПЕЦ-Ф-ТРАНС, ООО
+38 (093) 7756...
...and so on.
编辑:从公司页面获取头衔/电话:
import requests
from bs4 import BeautifulSoup
url = "https://www.ua-region.com.ua/ru/43434454"
soup = BeautifulSoup(requests.get(url).content, "html.parser")
sidebar = soup.select_one(".company-item-sidebar")
name = sidebar.select_one('span:-soup-contains("Юридическое название")')
name = name.find_next(text=True) if name else "N/A"
telephones = sidebar.select_one('span:-soup-contains("Телефоны")')
telephones = (
[a["href"] for a in telephones.find_next("div").find_all("a")]
if telephones
else []
)
# get other items here
# ...
print(name)
print(telephones)
print()
打印:
Юридическое название
['tel:+380636540215', 'tel:+380685496792', 'tel:+380952052509']