在Python网络抓取中需要帮助

时间:2020-03-22 13:14:10

标签: python web-scraping beautifulsoup

我写了一个简单的代码来抓取标题,地址,contct_person,电话号码和网站链接,但是我的程序只是抓取标题,我不知道如何抓取所有其他内容,因为它们没有类和ID。 / p>

这是我的代码:

import requests
from bs4 import BeautifulSoup
import csv

def get_page(url):
    response = requests.get(url)

    if not response.ok:
        print('server responded:', response.status_code)
    else:
        soup = BeautifulSoup(response.text, 'html.parser')
    return soup

def get_detail_data(soup):

    try:
        title = soup.find('a',class_="ListingDetails_Level1_SITELINK",id=False).text
    except:
        title = 'empty'  
    print(title)
    try:
        address = soup.find('div',class_="ListingDetails_Level1_CONTACTINFO",id=False).find_all('span').text
    except:
        address = "address"
    print(address)
    try:
        person_name = soup.find('a',class_="",id=False).find_all('img').text
    except:
        person_name = "empty person"
    print(person_name)
    try:
        phone_no = soup.find('img',class_="",id=False).text
    except:
        phone_no = "empty phone no"
    print(phone_no)
    try:
        website = soup.find('a',class_="",id=False).text
    except:
        website = "empty website"
    print(website)




def main():
    url = "https://secure.kelownachamber.org/Pools-Spas/Rocky%27s-Reel-System-Inc-4751"
    #get_page(url)
    get_detail_data(get_page(url))
if __name__ == '__main__':
    main()

2 个答案:

答案 0 :(得分:3)

以下代码对我有用(这只是向您展示如何从该网站获取数据,因此我将其保持简单):

import requests
from bs4 import BeautifulSoup
result = requests.get("https://secure.kelownachamber.org/Pools-Spas/Rocky%27s-Reel-System-Inc-4751")
src = result.content
soup = BeautifulSoup(src,'html.parser')
divs  = soup.find_all("div",attrs={"class":"ListingDetails_Level1_HEADERBOXBOX"})
for tag in divs:
  try:
   title = tag.find("a",attrs={"class":"ListingDetails_Level1_SITELINK"}).text
   address = tag.find("span",attrs={"itemprop":"street-address"}).text
   postal = tag.find("span",attrs={"itemprop":"postal-code"}).text
   maincontact = tag.find("span",attrs={"class":"ListingDetails_Level1_MAINCONTACT"}).text
   siteTag = tag.find("span",attrs={"class":"ListingDetails_Level1_VISITSITE"})
   site = siteTag.find("a").attrs['href']
   print(title)
   print(address) 
   print(postal)
   print(maincontact)
   print(site)
  except:
   pass

答案 1 :(得分:2)

如果您尝试使用Beautiful Soup抓取的页面元素没有类或ID,则可能很难告诉find()方法您要查找的内容。

在这种情况下,我更喜欢使用here中记录的select()select_one()。这些方法使您可以传递CSS选择器-用来告诉网络浏览器您想要以特定方式设置样式的元素的语法非常相似。

您可以找到有关here可用的选择器的参考。对于您的情况,我无法提供确切的CSS表达式,因为您没有提供要抓取的HTML样本,但这应该可以帮助您入门。

例如,如果您要抓取的页面看起来像这样:

<div id="contact">
    <div>
        <a href="ListingDetails_Level1_SITELINK">Some title</a>
    </div>

    <div>
        <p>1, Sesame St., Address...... </p>
    </div>
</div>

然后要获取地址,您可以使用CSS选择器,如下所示:

address = soup.select_one("#contact > div:nth-child(2) > p")

上面的代码说,可以通过在ID为“ contact”的div内的第二个div中查找该地址,然后在其中的段落中查找该地址。