Как очистить данные от нескольких тегов <br>с BeautifulSoup? - PullRequest
1 голос
/ 01 октября 2019

Как мне собрать данные из следующих пунктов, чтобы получить название компании, имя, адрес, город, почтовый индекс, телефон, адрес электронной почты, веб-сайт в виде различных столбцов? с https://directory.justice.org/SearchResult.asp?access=public&firstmiddlename=&middlename=&lastname=&maidenname=&firmname=&city=&provstateid=&zip=&countryid=&keyword=&areaofpractice=&areaofpractice2=Personal+Injury&sectiontype=&memtype=&sb=&gender=Any

Я хочу разделить детали юристов по различным тегам br, чтобы они были отдельными сущностями. Я застрял после нахождения подробностей адвокатов, как я могу назначить каждому тегу br значение, подобное имени? адрес и т. д.

    import pandas as pd
    from bs4 import BeautifulSoup, Tag
   import requests
  import re
     data =[]
     res=requests.get("https://directory.justice.org/SearchResult.asp?access=public&firstmiddlename=&middlename=&lastname=&maidenname=&firmname=&city=&provstateid=&zip=&countryid=&keyword=&areaofpractice=&areaofpractice2=Personal+Injury&sectiontype=&memtype=&sb=&gender=Any")
     soup=BeautifulSoup(res.text,'lxml')
     lawyers=soup.findAll('div',{'style':'float:left'})

Ответы [ 2 ]

2 голосов
/ 01 октября 2019

Попробуйте так:

from bs4 import BeautifulSoup, Tag, NavigableString
import pandas as pd
import requests


res=requests.get("https://directory.justice.org/SearchResult.asp?access=public&firstmiddlename=&middlename=&lastname=&maidenname=&firmname=&city=&provstateid=&zip=&countryid=&keyword=&areaofpractice=&areaofpractice2=Personal+Injury&sectiontype=&memtype=&sb=&gender=Any")

soup=BeautifulSoup(res.text,'lxml')
lawyers=soup.findAll('div',{'style':'float:left'})
roster = []
for law in lawyers:
    data = []
    for item in law:
        if isinstance(item, Tag) and len(item.text.strip())>0:
            data.append(item.text.strip())
        if isinstance(item, NavigableString):
            data.append(item.strip())
    roster.append(data)
df = pd.DataFrame(roster) 
df.head()
0 голосов
/ 01 октября 2019

Я также нашел альтернативный способ решить эту проблему:

import pandas as pd
from bs4 import BeautifulSoup, Tag
 import requests
 import re
data=[]
 res=requests.get("https://directory.justice.org/SearchResult.asp?access=public&firstmiddlename=&middlename=&lastname=&maidenname=&firmname=&city=&provstateid=&zip=&countryid=&keyword=&areaofpractice=&areaofpractice2=Personal+Injury&sectiontype=&memtype=&sb=&gender=Any")
 soup=BeautifulSoup(res.text,'lxml')
 lawyer=soup.findAll('div',{'style':'float:left'})
for item in lawyer:
    lawyer_company=(item.contents[0].text)
    lawyer_name=(item.contents[2])
    lawyer_address=(item.contents[4])
    lawyer_city=(item.contents[6])
    lawyer_state=(item.contents[6])
    lawyer_zip=(item.contents[6])

    lawyer_phone=(item.contents[8])
    lawyer_email=(item.contents[11])
    if isinstance(lawyer_email, Tag):
              lawyer_email=lawyer_email.text.strip()
    lawyer_website=(item.contents[13])
    if isinstance(lawyer_website, Tag):
              lawyer_website=lawyer_website.text.strip()
    full_dict={'Company':lawyer_company, 'Name':lawyer_name,'Address':lawyer_address,'City':lawyer_city,'State':lawyer_state,'Zip':lawyer_zip,'Phone':lawyer_phone,'Email':lawyer_phone,'Website':lawyer_website}
    data.append(full_dict)


 df=pd.DataFrame(data)
 print(df)
...