首页 > 解决方案 > Python xlsx 和网页抓取

问题描述

我有一个 Excel 文件,其中包含 400 多家公司的列表,我想打印公司名称并通过 Google.com 中的网络抓取获取公司的每个链接。你能帮我解决这个问题吗

我不知道如何附加我的excel文件。但这里是截图:

在此处输入图像描述

我想通过同时在google上搜索来获取每个公司的链接,并创建一个所有链接的excel文件。这就是我正在做的事情。但它只得到一个。

标签: python-3.xweb-scrapingxlsxpygooglechart

解决方案


我不确定这是什么意思:'每家公司主页的所有链接'。由于您没有提供任何示例 URL,我将仅使用几个通用 URL 来演示这一点,以说明这个想法。

下面是 Python 中的一个想法。这接近你想要的吗?

from bs4 import BeautifulSoup
import urllib.request

for numb in ('1', '10'):
    resp = urllib.request.urlopen("https://realfood.tesco.com/search.html?DietaryOption=Vegetarian")
    soup = BeautifulSoup(resp, from_encoding=resp.info().get_param('charset'))

    for link in soup.find_all('a', href=True):
        print(link['href'])

Result:
/recipes.html
/recipes/recipe-binder.html
/top-10s.html
/helpful-lists.html
/step-by-steps.html
/recipes/collections.html
/healthy-recipes.html
/recipes/collections/family-favourites-recipes.html
/recipes/collections/on-a-budget.html
/recipes/collections/crowd-pleasers.html
/recipes/collections.html#subcategories
/recipes/courses.html
/recipes/courses/breakfast-recipes.html
/recipes/courses/lunch-recipes.html
/recipes/courses/dinner-recipes.html
/recipes/courses/dessert-recipes.html
/recipes/courses.html#subcategories
/recipes/events.html

或者,下面是一个使用 VBA 的想法。这接近你想要的吗?

Sub HREF_Web()

Dim doc As HTMLDocument
Dim output As Object

Set IE = New InternetExplorer
IE.Visible = False
IE.navigate Range("L1")

Do
'DoEvents
Loop Until IE.readyState = READYSTATE_COMPLETE

Set doc = IE.document
Set output = doc.getElementsByTagName("a")

i = 5

For Each link In output
    'If link.InnerHTML = "" Then
        Range("A" & i).Value2 = link
   ' End If
   i = i + 1
Next

MsgBox "Done!"

End Sub

电子表格:

在此处输入图像描述


推荐阅读