首页 > 解决方案 > 使用 Soup 和 Python 抓取搜索结果,Split 只返回一个值而不是列表?

问题描述

尝试使用 Soup 和 Python 3.0x+ 抓取 google 搜索结果时,拆分后的结果只有一个值,即多个 URL 中的一个 URL。

预期输出是找到的所有 url 的列表,而不是一个,然后将使用 head,sep,tail 分区方法进行清理。

它发生在这个 for 循环之后。

 for link in links:
  x = re.split('="/url?q="',link["href"].replace("/url?q=",""))

值 links 具有来自搜索页面的所有结果,并且循环应该使用参数 link 遍历所有链接:

完整代码

import requests
from urllib.parse import urlparse 
import re
from bs4 import BeautifulSoup
import urllib.request



srchTerm = ['64503']



class AppURLopener(urllib.request.FancyURLopener):
      version = "Mozilla/5.0"

opener = AppURLopener()
parser = 'html.parser'  # or 'lxml' (preferred) or 'html5lib', if installed

for term in srchTerm:
 resp = opener.open("https://www.google.com/search?q=site:https://private.xx.co.bd/++" + term)

soup = BeautifulSoup(resp, parser, from_encoding=resp.info().get_param('charset'))
links = soup.find_all("a",href=re.compile("(?<=/url\?q=)(https://private.xx.co.bd/)"))

for link in links:
       x = re.split('="/url?q="',link["href"].replace("/url?q=",""))



## for linka in x: 
           ##head, sep, tail = linka.('&sa')
           ##print(head)

这仅打印一个结果:

<a data-uch="1" href="/url?q=https://private.xx.co.bd/blalbalba/4B1041344.aspx&amp;sa=U&amp;ved=2ahUKEwi-pOWSv4HqAhWGJTQIHUI-BCgQFjACegQIAxAB&amp;usg=AOvVaw3joBh4SH9QwW5WHmwn-7cs"><h3 class="zBAuLc"><div class="BNeawe vvjwJb AP7Wnd"><span dir="rtl">xxxxxxx</span></div></h3><div class="BNeawe UPmit AP7Wnd"><span dir="rtl">xxx‹ https://private.xxx.co.il</span></div></a>

标签: pythonweb-scrapingbeautifulsoupsplit

解决方案


推荐阅读