使用get函数无法获取相对应的标签

在爬取网页时,使用BeautifulSoup的.get('href')无法获取a标签链接,原因是.findall()返回列表,需通过索引访问。解决方法是使用d[0].get('href'),注意默认url需要结合当前域名处理。同时,.string可获取中文内容。
摘要由CSDN通过智能技术生成
# -*- coding: utf-8 -*-
import requests
import pandas as pd
from bs4 import BeautifulSoup
import re
import json
#import cx_Oracle
from sqlalchemy import create_engine
import sys

url = 'http://www.sac.net.cn/hyfw/hydt/'
for i in range(1):
    if i ==0:
        url1='http://www.sac.net.cn/hyfw/hydt/index.html'
    else:
        url1=url+'index_'+str(i)+'.html'
    print url1
    user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
    directory = {'User-Agent': user_agent}
    response = requests.get(url1, headers=directory)
    # 告诉他这段文本是以utf8方式编码 所以要以utf8方式解码
    response.encoding = 'utf-8'
    bs = BeautifulSoup(response.text, 'html.parser')
    title = bs.find('title').string[5:12]
    print title
    print url[0:21]
    table = bs.find_all('table')
    for a in table:
        b = a.find_all(&#
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值