Вам придется немного поработать, так как адрес не найден для всех сайтов.Но я получил это зацикливание.Кроме того, некоторые запросы получают ответ 404.
Я немного поработал, чтобы он повторил различные результаты поиска.Может быть, не совсем то, что вы ищете, но, возможно, дает вам кое-что для работы.Я думаю, что, по крайней мере, вы можете найти несколько адресов, и, возможно, у вас останется лишь горстка, которую вам нужно будет найти и найти вручную:
from bs4 import BeautifulSoup as BS
import requests
from googlesearch import search
from googleapiclient.discovery import build
import re
companylist = ['ARTA Management für das Handwerk GmbH + Co.', "aktive Stuttgarter", 'ABEX Dachdecker Handwerks-GmbH',
'Academie für Kunst und Handwerk e.V.', 'AHA Agentur fürs Handwerk GmbH']
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36'}
not_found = []
for com in companylist:
url_list = []
for url in search(com, tld='de', lang='de', stop=50):
url_list.append(url)
found_contact = False
for url2 in url_list:
next_url = False
while found_contact == False and next_url == False:
try:
webSite = requests.get(url2+'kontakt', headers=headers)
if webSite.status_code == 200:
soup = BS(webSite.content, 'html.parser')
string = ''
for line in soup.findAll('p'):
string = string + line.text + ' '
match = re.search(r'\s\w+\s\Straße\s\w+\s\w+\s\w+\s', string)
try:
print('Found: %s\n%s' %(com,match.group().strip()),'\n')
found_contact = True
next_url = True
if com in not_found:
del not_found[com]
continue
except:
print('Attempt: %s of %s: Address not found for: %s' %(url_list.index(url2)+1, len(url_list),com))
next_url = True
if com not in not_found:
not_found.append(com)
else:
next_url = True
print('Attempt: %s of %s: Address not found for: %s' %(url_list.index(url2)+1, len(url_list),com))
except:
next_url = True
print('Attempt: %s of %s: Address not found for: %s' %(url_list.index(url2)+1, len(url_list),com))
Additioanl:
Не самый быстрый способ, но вы можете использовать Selenium для автоматического поиска этих компаний.
from bs4 import BeautifulSoup as BS
from selenium import webdriver
import requests
url = 'https://www.firmenwissen.de/index.html'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36'}
driver = webdriver.Chrome('C:/chromedriver_win32/chromedriver.exe')
driver.get(url)
companylist = ['ARTA Management für das Handwerk GmbH + Co.', "aktive Stuttgarter", 'ABEX Dachdecker Handwerks-GmbH',
'Academie für Kunst und Handwerk e.V.', 'AHA Agentur fürs Handwerk GmbH']
error = []
for company in companylist:
inputElement = driver.find_element_by_id("searchPhrase0")
inputElement.clear()
inputElement.send_keys(company)
inputElement.submit()
soup = BS(driver.page_source, 'html.parser')
link = soup.find('span',{'class':'company--name'})
a_link = link.find('a')['href']
response = requests.get('https://www.firmenwissen.de' + a_link + '?showEmail=true', headers=headers)
alpha_soup = BS(response.text, 'html.parser')
try:
phone = alpha_soup.find('span', {'class':'yp_phoneNumber'}).text.strip()
except:
phone = ''
try:
email = alpha_soup.find('span', {'class':'yp_email'}).text.strip()
except:
email = ''
try:
website = alpha_soup.find('span', {'class':'yp_website'}).text.strip()
except:
webiste = ''
try:
contact = soup.find('div', {'class':'company--info'})
address = contact.find_all('p')[-1].text.strip()
except:
print ('Could not locate %s company info' %(company))
error.append(company)
print('%s\n%s\n%s\n%s\n' %(address, phone, email, website))