BeautifulSoup和刮除href无效

时间:2018-09-15 15:34:30

标签: python beautifulsoup

同样,我在BeautifulSoup中刮取href时遇到了麻烦。我有要抓取的页面列表,并且有数据,但是即使我使用在其他脚本中可用的各种代码,也似乎无法获得hrefs。

所以这是代码,我的数据将在下面:

import requests
from bs4 import BeautifulSoup


with open('states_names.csv', 'r') as reader:
    states = [states.strip().replace(' ', '-') for states in reader]


url = 'https://www.hauntedplaces.org/state/alabama'

for state in states:
    page = requests.get(url+state)
    soup = BeautifulSoup(page.text, 'html.parser')
    links = soup.findAll('div', class_='description')
    # When I try to add .get('href') I get a traceback error. Am I trying to scrape the href too early? 
    h_page = soup.findAll('h3')

<h3><a href="https://www.hauntedplaces.org/item/gaines-ridge-dinner-club/">Gaines Ridge Dinner Club</a></h3>
<h3><a href="https://www.hauntedplaces.org/item/purifoy-lipscomb-house/">Purifoy-Lipscomb House</a></h3>
<h3><a href="https://www.hauntedplaces.org/item/kate-shepard-house-bed-and-breakfast/">Kate Shepard House Bed and Breakfast</a></h3>
<h3><a href="https://www.hauntedplaces.org/item/cedarhurst-mansion/">Cedarhurst Mansion</a></h3>
<h3><a href="https://www.hauntedplaces.org/item/crybaby-bridge/">Crybaby Bridge</a></h3>
<h3><a href="https://www.hauntedplaces.org/item/gaineswood-plantation/">Gaineswood Plantation</a></h3>
<h3><a href="https://www.hauntedplaces.org/item/mountain-view-hospital/">Mountain View Hospital</a></h3>

2 个答案:

答案 0 :(得分:1)

这很完美:

from bs4 import BeautifulSoup
import requests

url = 'https://www.hauntedplaces.org/state/Alabama'

r = requests.get(url)
soup = BeautifulSoup(r.text, 'lxml')

for link in soup.select('div.description a'):
    print(link['href'])

答案 1 :(得分:0)

尝试:

soup = BeautifulSoup(page.content, 'html.parser')
list0 = []   
possible_links = soup.find_all('a')
for link in possible_links:
    if link.has_attr('href'):
        print (link.attrs['href'])
        list0.append(link.attrs['href'])
print(list0)